API Reference#
Data I/O#
- class circstudio.io.base.Raw(df, period, frequency, activity, light, fpath=None, start_time=None, stop_time=None)[source]#
Bases:
MaskBase class for raw actigraphy data.
- plot(mode='activity', ts=None, log=False)[source]#
Plot a time series from actigraphy data.
This method generates an interactive Plotly graph of either activity, light, or a custom time series extracted from the dataframe stored in the Raw object. By default, it plots raw activity data.
- Parameters:
ts (str, optional) – Name of the custom time series column to plot.
mode (str, optional) –
- Type of data to plot. Must be one of:
’activity’: plot the activity signal
’light’: plot the light signal
’mask’: plot the mask signal
None: plot custom signal (ts must not be None)
log (bool) – Whether to apply a log transformation to the data (log10(x+1)) before plotting.
- Returns:
A Plotly Figure object corresponding to a time series.
- Return type:
go.Figure
- read_sleep_diary(input_fname, header_size=2, state_index=None, state_colour=None)[source]#
Reader function for sleep diaries.
- Parameters:
input_fname (str) – Path to the sleep diary file.
header_size (int) – Header size (i.e. number of lines) of the sleep diary. Default is 2.
state_index (dict) – Dictionnary of state’s indices.
state_color (dict) – Dictionnary of state’s colours.
- class circstudio.io.mask.BaseLog(input_fname, log)[source]#
Bases:
objectRead and store time intervals (start/stop times) from a “log file”.
In circadian/actigraphy analysis workflows, you often keep a separate log describing periods to exclude or flag, e.g.: - Naps or bedtimes recorded manually - Mask periods suspected of being spurious inactivity (e.g., non-wear)
This class reads a table with three columns: - An identifier (e.g., “Mask”, “Nap”, “Event”) used as the row index. - Start time (datetime) - Stop time (datetime)
After reading, the log is stored as a pandas DataFrame with an additional column: Duration = Stop_time - Start_Time
Supported file formats#
CSV: .csv
Spreadsheet-like: .xlsx, .xls, .ods (via pyexcel)
- param input_fname:
Path to the input log file (relative or absolute).
- type input_fname:
str
- param log:
A DataFrame containing at least: - Start_time (datetime64) - Stop_time (datetime64)
- type log:
pandas.DataFrame
- fname#
Absolute path to the log file used.
- Type:
str
- log#
Cleaned log table with columns
Start_time,Stop_time, andDuration.- Type:
pandas.DataFrame
- property fname#
The absolute filepath of the input log file.
- classmethod from_file(input_fname, index_name, *args, **kwargs)[source]#
Read start/stop-times from log files.
Generic function to read start and stop times from log files. Supports different file format (.ods, .xls(x), .csv).
- Parameters:
input_fname (str) – Path to the log file.
index_name (str) – Name of the index.
*args – Variable length argument list passed to the subsequent reader function.
**kwargs – Arbitrary keyword arguments passed to the subsequent reader function.
- Returns:
absname (str) – Absolute filepath of the input log file.
log (pandas.DataFrame) – Dataframe containing the data found in the log file.
- property log#
The dataframe containing the data found in the log file.
- class circstudio.io.mask.Mask(exclude_if_mask, mask_inactivity, binarize, threshold, inactivity_length, mask)[source]#
Bases:
objectMixin that adds masking + preprocessing for actigraphy/light time series.
This class is designed to be mixed into a higher-level recording object that already provides:
Required attributes on the host class#
activitypandas.Series or NoneActivity counts indexed by time (DatetimeIndex).
lightpandas.Series or NoneLight intensity (e.g., lux) indexed by time (DatetimeIndex).
frequencypandas.TimedeltaSampling epoch (e.g., 30 seconds, 1 minute).
start_timepandas.TimestampBeginning of the analysis window.
periodpandas.TimedeltaDuration of the analysis window.
What a “mask” means#
A mask is a time series aligned to the data index (same timestamps), typically: - 1 = keep the data point - 0 = exclude the data point (e.g., non-wear, sensor failure)
Masking is commonly used to remove long stretches of zero activity that likely represent device removal, not true sleep/inactivity.
Key features#
Auto-create an inactivity mask: flag sustained “zero-activity” stretches.
Manually add mask intervals using start/stop times.
- Apply preprocessing filters:
resampling to a new epoch
binarization (thresholding)
optional missing-data imputation
mask-based exclusion
- param exclude_if_mask:
If True, masked samples are excluded downstream (e.g., set to NaN or removed, depending on the processing function).
- type exclude_if_mask:
bool
- param mask_inactivity:
If True, apply the inactivity mask when filtering.
- type mask_inactivity:
bool
- param binarize:
If True, binarize the signal using
threshold.- type binarize:
bool
- param threshold:
Threshold used when
binarize=True.- type threshold:
float
- param inactivity_length:
Minimum number of consecutive zero-activity epochs to be considered “inactivity” (potential non-wear). If None, no inactivity mask is created automatically.
- type inactivity_length:
int or None
- param mask:
A precomputed mask series aligned to the data index (1=keep, 0=exclude).
- type mask:
pandas.Series or None
- mask#
Mask aligned to the current analysis window. If no mask exists but
inactivity_lengthis set, it is created automatically on first access.- Type:
pandas.Series
- inactivity_length#
Minimum consecutive zero epochs defining an inactivity segment.
- Type:
int or None
- add_mask_period(start, stop)[source]#
Add a period to the inactivity mask
- Parameters:
start (str) – Start time (YYYY-MM-DD HH:MM:SS) of the inactivity period.
stop (str) – Stop time (YYYY-MM-DD HH:MM:SS) of the inactivity period.
- add_mask_periods(input_fname, *args, **kwargs)[source]#
Add periods to the inactivity mask
Function to read start and stop times from a Mask log file. Supports different file format (.ods, .xls(x), .csv).
- Parameters:
input_fname (str) – Path to the log file.
*args – Variable length argument list passed to the subsequent reader function.
**kwargs – Arbitrary keyword arguments passed to the subsequent reader function.
- apply_filters(new_freq=None, binarize=False, threshold=0, apply_mask=False, impute_nan=False, exclude_if_mask=False, imputation_method='mean')[source]#
Apply preprocessing to activity and/or light time series.
This method optionally: - Resamples the data to a new epoch length (e.g., 30s to 1 min). - Binarizes using a threshold - Applies masking (exclude masked samples) - Impute missing values
- Parameters:
new_freq (str or pandas offset, optional) – New epoch length (e.g., “1min”, “30s”). If None, keep current frequency.
binarize (bool) – If True, binarize values using
threshold.threshold (float) – Threshold for binarization.
apply_mask (bool) – If True, apply the current mask (and create inactivity mask if configured).
impute_nan (bool) – If True, fill NaNs using
imputation_method.exclude_if_mask (bool) – If True, masked values are excluded (implementation depends on the processing backend).
imputation_method ({"mean", "median", ...}) – Strategy for filling missing values.
- create_inactivity_mask(duration)[source]#
Create a mask for inactivity (count equal to zero) periods.
This mask has the same length as its underlying data and can be used to obfuscate inactive periods where the actimeter has most likely been removed. Warning: use a sufficiently long duration in order not to mask sleep periods. A minimal duration corresponding to two hours seems reasonable.
- Parameters:
duration (int or str) – Minimal number of consecutive zeroes for an inactive period. Time offset strings (ex: ‘90min’) can also be used.
- property inactivity_length#
Length of the inactivity mask.
- property mask#
Mask used to filter out inactive data.
Rest-Activity Metrics#
- circstudio.analysis.metrics.metrics.IS(data)[source]#
Interdaily stability
The Interdaily stability (IS) quantifies the repeatibilty of the daily rest-activity pattern over each day contained in the activity recording.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
is
- Return type:
float
Notes
This variable is defined in ref [1]_:
\[IS = \frac{d^{24h}}{d^{1h}}\]with:
\[d^{1h} = \sum_{i}^{n}\frac{\left(x_{i}-\bar{x}\right)^{2}}{n}\]where \(x_{i}\) is the number of active (counts higher than a predefined threshold) minutes during the \(i^{th}\) period, \(\bar{x}\) is the mean of all data and \(n\) is the number of periods covered by the actigraphy data and with:
\[d^{24h} = \sum_{i}^{p} \frac{ \left( \bar{x}_{h,i} - \bar{x} \right)^{2} }{p}\]where \(\bar{x}^{h,i}\) is the average number of active minutes over the \(i^{th}\) period and \(p\) is the number of periods per day. The average runs over all the days.
For the record, tt is the 24h value from the chi-square periodogram (Sokolove and Bushel1 1978).
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Witting W., Kwa I.H., Eikelenboom P., Mirmiran M., Swaab D.F. Alterations in the circadian rest–activity rhythm in aging and Alzheimer׳s disease. Biol Psychiatry. 1990;27:563–572.
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.ISp(data, period='7D', verbose=False)[source]#
Interdaily stability per period
The IS is calculated for each consecutive period found in the actigraphy recording.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
period (str, optional) – Time period for the calculation of IS Default is ‘7D’.
verbose (bool, optional) – If set to True, display the number of periods found in the activity recording, as well as the time not accounted for. Default is False.
- Returns:
isp
- Return type:
list of float
Notes
Periods are consecutive and all of the required duration. If the last consecutive period is shorter than required, the IS is not calculated for that period.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.IV(data)[source]#
Intradaily variability
The Intradaily Variability (IV) quantifies the variability of the activity recording. This variable thus measures the rest or activity fragmentation.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
iv
- Return type:
float
Notes
It is defined in ref [1]_:
\[IV = \frac{c^{1h}}{d^{1h}}\]with:
\[d^{1h} = \sum_{i}^{n}\frac{\left(x_{i}-\bar{x}\right)^{2}}{n}\]where \(x_{i}\) is the number of active (counts higher than a predefined threshold) minutes during the \(i^{th}\) period, \(\bar{x}\) is the mean of all data and \(n\) is the number of periods covered by the actigraphy data,
and with:
\[c^{1h} = \sum_{i}^{n-1} \frac{ \left( x_{i+1} - x_{i} \right)^{2} }{n-1}\]References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Witting W., Kwa I.H., Eikelenboom P., Mirmiran M., Swaab D.F. Alterations in the circadian rest–activity rhythm in aging and Alzheimer׳s disease. Biol Psychiatry. 1990;27:563–572.
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.IVp(data, period='7D', verbose=False)[source]#
Intradaily variability per period
The IV is calculated for each consecutive period found in the actigraphy recording.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
period (str, optional) – Time period for the calculation of IS Default is ‘7D’.
verbose (bool, optional) – If set to True, display the number of periods found in the activity recording, as well as the time not accounted for. Default is False.
- Returns:
ivp
- Return type:
list of float
Notes
Periods are consecutive and all of the required duration. If the last consecutive period is shorter than required, the IV is not calculated for that period.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.TAT(data, threshold=None, start_time=None, stop_time=None, oformat=None)[source]#
Time above light threshold.
Calculate the total light exposure time above the threshold.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
threshold (float, optional) – If not set to None, discard data below threshold before computing exposure levels. Default is None.
start_time (str, optional) – If not set to None, discard data before start time, on a daily basis. Supported time string: ‘HH:MM:SS’ Default is None.
stop_time (str, optional) – If not set to None, discard data after stop time, on a daily basis. Supported time string: ‘HH:MM:SS’ Default is None.
oformat (str, optional) – Output format. Available formats: ‘minute’ or ‘timedelta’. If set to ‘minute’, the result is in number of minutes. If set to ‘timedelta’, the result is a pd.Timedelta. If set to None, the result is in number of epochs. Default is None.
- Returns:
tat – A pandas Series with aggreagted light exposure levels per channel
- Return type:
pd.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.TATp(data, threshold=None, start_time=None, stop_time=None, oformat=None)[source]#
Time above light threshold (per day).
Calculate the total light exposure time above the threshold, per calendar day.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
threshold (float, optional) – If not set to None, discard data below threshold before computing exposure levels. Default is None.
start_time (str, optional) – If not set to None, discard data before start time, on a daily basis. Supported time string: ‘HH:MM:SS’ Default is None.
stop_time (str, optional) – If not set to None, discard data after stop time, on a daily basis. Supported time string: ‘HH:MM:SS’ Default is None.
oformat (str, optional) – Output format. Available formats: ‘minute’ or ‘timedelta’. If set to ‘minute’, the result is in number of minutes. If set to ‘timedelta’, the result is a pd.Timedelta. If set to None, the result is in number of epochs. Default is None.
- Returns:
tatp – A pandas DataFrame with aggreagted light exposure levels per channel and per day.
- Return type:
pd.DataFrame
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.VAT(data, threshold=None)[source]#
Values above light threshold.
Returns the light exposure values above the threshold.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
threshold (float, optional) – If not set to None, discard data below threshold before computing exposure levels. Default is None.
- Returns:
vat – A pandas Series with light exposure levels per channel
- Return type:
pd.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.adat(data, rescale=True, exclude_ends=False)[source]#
Total average daily activity
Calculate the total activity counts, averaged over all the days.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
rescale (bool, optional) – If set to True, the activity counts are rescaled to account for masked periods (if any). Default is True.
exclude_ends (bool, optional) – If set to True, the first and last daily periods are excluded from the calculation. Useful when the recording does start or end at midnigth. Default is False.
- Returns:
adat
- Return type:
int
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.adatp(data, period='7D', rescale=True, exclude_ends=False, verbose=False)[source]#
Total average daily activity per period
Calculate the total activity counts, averaged over each consecutive period contained in the data. The number of periods
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
period (str, optional) – Time length of the period to be considered. Must be understandable by pandas.Timedelta
rescale (bool, optional) – If set to True, the activity counts are rescaled to account for masked periods (if any). Default is True.
exclude_ends (bool, optional) – If set to True, the first and last daily periods are excluded from the calculation. Useful when the recording does start or end at midnigth. Default is False.
verbose (bool, optional) – If set to True, display the number of periods found in the data. Also display the time not accounted for. Default is False.
- Returns:
adatp
- Return type:
list of int
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.daily_profile(data, cyclic=False, time_origin=None, whs='1h', plot=False, log=False)[source]#
Average daily activity/light/temperature distribution
Calculate the daily profile of activity. Data are averaged over all the days.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
cyclic (bool, optional) – If set to True, two daily profiles are concatenated to ensure continuity between the last point of the day and the first one. Default is False.
time_origin (str or pd.Timedelta, optional) – If not None, origin of the time axis for the daily profile. Original time bins are translated as time delta with respect to this new origin. Default is None Supported time string: ‘AonT’, ‘AoffT’, any ‘HH:MM:SS’
whs (str, optional) – Window half size parameter for the detection of the activity onset/offset time. Relevant only if time_origin is set to ‘AonT’ or AoffT’. Default is ‘1h’.
plot (bool, optional) – Whether to plot the daily profile. Default is False.
log (bool, optional) – Whether the daily profile should be transformed to a log10 scale.
- Returns:
raw – A Series containing the daily activity profile with a 24h index.
- Return type:
pandas.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.daily_profile_auc(data, start_time=None, stop_time=None, time_origin=None)[source]#
AUC of the average daily light profile
Calculate the area under the curve of the daily profile of light exposure. Data are averaged over all the days.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
start_time (str, optional) – If not set to None, compute AUC from start time. Supported time string: ‘HH:MM:SS’ Default is None.
stop_time (str, optional) – If not set to None, compute AUC until stop time. Supported time string: ‘HH:MM:SS’ Default is None.
time_origin (str or pd.Timedelta, optional) – If not None, origin of the time axis for the daily profile. Original time bins are translated as time delta with respect to this new origin. Default is None Supported time string: ‘HH:MM:SS’
- Returns:
auc – Area under the curve.
- Return type:
float
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.get_extremum(data, extremum)[source]#
Light extremum.
Return the index and the value of the requested extremum (min or max).
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
extremum (str) – Name of the extremum. Available: ‘min’ or ‘max’.
- Returns:
ext – A pandas DataFrame with extremum info per channel.
- Return type:
pd.DataFrame
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.kAR(data, start=None, period=None, frac=0.3, it=0, logit=False, offset='15min')[source]#
Rest->Activity transition probability
Weighted average value of pAR(t) within the constant regions, defined as the longest stretch within which the LOWESS curve varied by no more than 1 standard deviation of the pAR(t) curve.
- Parameters:
threshold (int) – Above this threshold, data are classified as active (1) and as rest (0) otherwise.
start (str, optional) – If not None, the actigraphy recording is truncated to ‘start:start+period’, each day. Start string format: ‘HH:MM:SS’. Special keywords (‘AonT’ or ‘AoffT’) are allowed. In this case, the start is set to the activity onset (‘AonT’) or offset (‘AoffT’) time derived from the daily profile. Cf sleep.AonT/AoffT functions for more informations. Default is None
period (str, optional) – Time period for the calculation of pRA. Default is None.
frac (float) – Fraction of the data used when estimating each value. Default is 0.3.
it (int) – Number of residual-based reweightings to perform. Default is 0.
logit (bool, optional) – If True, the kRA value is logit-transformed (ln(p/1-p)). Useful when kRA is used in a regression model. Default is False.
freq (str, optional) – Data resampling frequency string applied to the daily profile if start=’AonT’ or ‘AoffT’. Default is None.
offset (str, optional) – Time offset with respect to the activity onset and offset times used as start times. Default is ‘15min’.
- Returns:
kar
- Return type:
float
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Lim, A. S. P., Yu, L., Costa, M. D., Buchman, A. S., Bennett, D. A., Leurgans, S. E., & Saper, C. B. (2011). Quantification of the Fragmentation of Rest-Activity Patterns in Elderly Individuals Using a State Transition Analysis. Sleep, 34(11), 1569–1581. http://doi.org/10.5665/sleep.1400
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.kRA(data, start=None, period=None, frac=0.3, it=0, logit=False, offset='15min')[source]#
Rest->Activity transition probability
Weighted average value of pRA(t) within the constant regions, defined as the longest stretch within which the LOWESS curve varied by no more than 1 standard deviation of the pRA(t) curve [1]_.
- Parameters:
threshold (int) – Above this threshold, data are classified as active (1) and as rest (0) otherwise.
start (str, optional) – If not None, the actigraphy recording is truncated to ‘start:start+period’, each day. Start string format: ‘HH:MM:SS’. Special keywords (‘AonT’ or ‘AoffT’) are allowed. In this case, the start is set to the activity onset (‘AonT’) or offset (‘AoffT’) time derived from the daily profile. Cf sleep.AonT/AoffT functions for more informations. Default is None
period (str, optional) – Time period for the calculation of pRA. Default is None.
frac (float, optional) – Fraction of the data used when estimating each value. Default is 0.3.
it (int, optional) – Number of residual-based reweightings to perform. Default is 0.
logit (bool, optional) – If True, the kRA value is logit-transformed (ln(p/1-p)). Useful when kRA is used in a regression model. Default is False.
offset (str, optional) – Time offset with respect to the activity onset and offset times used as start times. Default is ‘15min’.
- Returns:
kra
- Return type:
float
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Lim, A. S. P., Yu, L., Costa, M. D., Buchman, A. S., Bennett, D. A., Leurgans, S. E., & Saper, C. B. (2011). Quantification of the Fragmentation of Rest-Activity Patterns in Elderly Individuals Using a State Transition Analysis. Sleep, 34(11), 1569–1581. http://doi.org/10.5665/sleep.1400
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.l5(data)[source]#
L5
Mean activity/temperature/light, etc., during the 5 least active hours of the day.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
l5_onset, l5
- Return type:
float
Notes
The L5 [1]_ variable is calculated as the mean, per acquisition period, of the average daily activities during the 5 least active hours.
Warning
The value of this variable depends on the length of the
acquisition period.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.l5p(data, period='7D', verbose=False)[source]#
L5 per period
The L5 variable is calculated for each consecutive period found in the actigraphy recording.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
period (str, optional) – Time period for the calculation of IS Default is ‘7D’.
verbose (bool, optional) – If set to True, display the number of periods found in the activity recording, as well as the time not accounted for. Default is False.
- Returns:
l5p
- Return type:
list of float
Notes
The L5 [1]_ variable is calculated as the mean, per acquisition period, of the average daily activities during the 5 least active hours.
Warning
The value of this variable depends on the length of the acquisition period.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.light_exposure(light, threshold=None, start_time=None, stop_time=None, agg='mean')[source]#
Light exposure level
Calculate the aggregated (mean, median, etc) light exposure level per epoch.
- Parameters:
light (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (in this case, light). Time and value arrays are extracted from this series.
threshold (float, optional) – If not set to None, discard data below threshold before computing exposure levels. Default is None.
start_time (str, optional) – If not set to None, discard data before start time, on a daily basis. Supported time string: ‘HH:MM:SS’ Default is None.
stop_time (str, optional) – If not set to None, discard data after stop time, on a daily basis. Supported time string: ‘HH:MM:SS’ Default is None.
agg (str, optional) – Aggregating function used to summarize exposure levels. Available functions: ‘mean’, ‘median’, ‘std’, etc. Default is ‘mean’.
- Returns:
levels – A pandas Series with aggreagted light exposure levels per channel
- Return type:
pd.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.lmx(data, length='5h', lowest=True)[source]#
Least or Most light period of length X
Onset and mean hourly light exposure levels during the X least or most bright hours of the day.
- Parameters:
data (pandas.Series) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
length (str, optional) – Period length. Default is ‘5h’.
lowest (bool, optional) – If lowest is set to True, the period of least light exposure is considered. Otherwise, consider the period of most light exposure. Default is True.
- Returns:
lmx_t, lmx – Onset and mean hourly light exposure level.
- Return type:
(pd.Timedelta, float)
Notes
The LMX variable is derived from the L5 and M10 defined in [1]_ as the mean hourly activity levels during the 5/10 least/most active hours.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.m10(data)[source]#
M10
Mean activity/light/temperature, etc. during the 10 most active hours of the day.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
m10_onset, m10
- Return type:
float
Notes
The M10 [1]_ variable is calculated as the mean, per acquisition period , of the average daily activities during the 10 most active hours.
Warning
The value of this variable depends on the length of the acquisition period.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.m10p(data, period='7D', verbose=False)[source]#
M10 per period
The M10 variable is calculated for each consecutive period found in the actigraphy recording.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
period (str, optional) – Time period for the calculation of IS Default is ‘7D’. If set to True, display the number of periods found in the activity recording, as well as the time not accounted for. Default is False.
verbose (bool, optional) – If set to True, display the number of periods found in the activity recording, as well as the time not accounted for. Default is False.
- Returns:
m10p
- Return type:
list of float
Notes
The M10 [1]_ variable is calculated as the mean, per acquisition period , of the average daily activities during the 10 most active hours.
Warning
The value of this variable depends on the length of the acquisition period.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.mlit(light, threshold)[source]#
Mean light timing.
Mean light timing above threshold, MLiT^C.
- Parameters:
light (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (in this case, light). Time and value arrays are extracted from this series.
threshold (float) – Threshold value.
- Returns:
MLiT – A pandas DataFrame with MLiT^C per channel.
- Return type:
pd.DataFrame
Notes
The MLiT variable is defined in ref [1]_:
\[MLiT^C = \frac{\sum_{j}^{m}\sum_{k}^{n} j\times I^{C}_{jk}}{ \sum_{j}^{m}\sum_{k}^{n} I^{C}_{jk}}\]where \(I^{C}_{jk}\) is equal to 1 if the light level is higher than the threshold C, m is the total number of epochs per day and n is the number of days covered by the data.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Reid K.J., Santostasi G., Baron K.G., Wilson J., Kang J., Zee P.C., Timing and Intensity of Light Correlate with Body Weight in Adults. PLoS ONE 9(4): e92251. https://doi.org/10.1371/journal.pone.0092251
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.mlitp(light, threshold)[source]#
Mean light timing per day.
Mean light timing above threshold, MLiT^C, per calendar day.
- Parameters:
light (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (in this case, light). Time and value arrays are extracted from this series.
threshold (float) – Threshold value.
- Returns:
MLiTp – A pandas DataFrame with MLiT^C per channel and per day.
- Return type:
pd.DataFrame
Notes
The MLiT variable is defined in ref [1]_:
\[MLiT^C = \frac{\sum_{j}^{m}\sum_{k}^{n} j\times I^{C}_{jk}}{ \sum_{j}^{m}\sum_{k}^{n} I^{C}_{jk}}\]where \(I^{C}_{jk}\) is equal to 1 if the light level is higher than the threshold C, m is the total number of epochs per day and n is the number of days covered by the data.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Reid K.J., Santostasi G., Baron K.G., Wilson J., Kang J., Zee P.C., Timing and Intensity of Light Correlate with Body Weight in Adults. PLoS ONE 9(4): e92251. https://doi.org/10.1371/journal.pone.0092251
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.pAR(data, start=None, period=None)[source]#
Activity->Rest transition probability distribution
Conditional probability, pAR(t), that an individual would be active at time (t+1) given that the individual had been continuously resting for the preceding t epochs, defined in [1]_ as:
\[pAR(t) = p(R|A_t) = \frac{N_t - N_{t+1}}{N_t}\]with \(N_t\), the total number of sequences of activity (i.e. activity above threshold) of duration \(t\) or longer.
- Parameters:
threshold (int) – If binarize is set to True, data above this threshold are set to 1 and to 0 otherwise.
start (str, optional) – If not None, the actigraphy recording is truncated to ‘start:start+period’, each day. Start string format: ‘HH:MM:SS’. Default is None
period (str, optional) – Time period for the calculation of pAR. Default is None.
- Returns:
par (pandas.core.series.Series) – Transition probabilities (pAR(t)), calculated for all t values.
par_weights (pandas.core.series.Series) – Weights are defined as the square root of the number of activity sequences contributing to each probability estimate.
Notes
pAR is corrected for discontinuities due to sparse data, as defined in [1]_.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Lim, A. S. P., Yu, L., Costa, M. D., Buchman, A. S., Bennett, D. A., Leurgans, S. E., & Saper, C. B. (2011). Quantification of the Fragmentation of Rest-Activity Patterns in Elderly Individuals Using a State Transition Analysis. Sleep, 34(11), 1569–1581. http://doi.org/10.5665/sleep.1400
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.pRA(data, start=None, period=None)[source]#
Rest->Activity transition probability distribution
Conditional probability, pRA(t), that an individual would be resting at time (t+1) given that the individual had been continuously active for the preceding t epochs, defined in [1]_ as:
\[pRA(t) = p(A|R_t) = \frac{N_t - N_{t+1}}{N_t}\]with \(N_t\), the total number of sequences of rest (i.e. activity below threshold) of duration \(t\) or longer.
- Parameters:
threshold (int) – If binarize is set to True, data above this threshold are set to 1 and to 0 otherwise.
start (str, optional) – If not None, the actigraphy recording is truncated to ‘start:start+period’, each day. Start string format: ‘HH:MM:SS’. Default is None
period (str, optional) – Time period for the calculation of pRA. Default is None.
- Returns:
pra (pandas.core.series.Series) – Transition probabilities (pRA(t)), calculated for all t values.
pra_weights (pandas.core.series.Series) – Weights are defined as the square root of the number of activity sequences contributing to each probability estimate.
Notes
pRA is corrected for discontinuities due to sparse data, as defined in [1]_.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Lim, A. S. P., Yu, L., Costa, M. D., Buchman, A. S., Bennett, D. A., Leurgans, S. E., & Saper, C. B. (2011). Quantification of the Fragmentation of Rest-Activity Patterns in Elderly Individuals Using a State Transition Analysis. Sleep, 34(11), 1569–1581. http://doi.org/10.5665/sleep.1400
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.ra(data)[source]#
Relative rest/activity amplitude
Relative amplitude between the mean activity during the 10 most active hours of the day and the mean activity during the 5 least active hours of the day.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
ra
- Return type:
float
Notes
The RA [1]_ variable is calculated as:
\[RA = \frac{M10 - L5}{M10 + L5}\]References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.rap(data, period='7D', verbose=False)[source]#
RA per period
The RA variable is calculated for each consecutive period found in the actigraphy recording.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
period (str, optional) – Time period for the calculation of IS Default is ‘7D’.
verbose (bool, optional) – If set to True, display the number of periods found in the activity recording, as well as the time not accounted for. Default is False.
- Returns:
rap
- Return type:
list of float
Notes
The RA [1]_ variable is calculated as:
\[RA = \frac{M10 - L5}{M10 + L5}\]References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Van Someren, E.J.W., Lijzenga, C., Mirmiran, M., Swaab, D.F. (1997). Long-Term Fitness Training Improves the Circadian Rest-Activity Rhythm in Healthy Elderly Males. Journal of Biological Rhythms, 12(2), 146–156. http://doi.org/10.1177/074873049701200206
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.spectral_centroid(data)[source]#
Compute the spectral centroid of a time series.
- Parameters:
data (pandas.Series) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
The spectral (frequency) centroid of the time series, expressed as a timestamp.
- Return type:
pd.Timestamp
References
[1] Zauner, J., Hartmeyer, S., & Spitschan, M. (2025). LightLogR: Reproducible analysis of personal light exposure data. Journal of Open Source Software, 10(107), 7601. https://doi.org/10.21105/joss.07601. RRID:SCR_025408
- circstudio.analysis.metrics.metrics.summary_stats(light, bins='24h', agg_func=None)[source]#
Summary statistics.
Calculate summary statistics (ex: mean, median, etc) according to a user-defined (regular or arbitrary) binning.
- Parameters:
light (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (in this case, light). Time and value arrays are extracted from this series.
bins (str or list of tuples, optional) – If set to a string, bins is used to define a regular binning where every bin is of length “bins”. Ex: “2h”. Otherwise, the list of 2-tuples is used to define an arbitrary binning. Ex: [(‘2000-01-01 00:00:00’,’2000-01-01 11:59:00’)]. Default is ‘24h’.
agg_func (list, optional) – List of aggregation functions to be used on every bin. Default is [‘mean’, ‘median’, ‘sum’, ‘std’, ‘min’, ‘max’].
- Returns:
ss – A pandas DataFrame with summary statistics per channel.
- Return type:
pd.DataFrame
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.metrics.metrics.temporal_centroid(data)[source]#
Compute the temporal centroid of a time series.
The centroid is calculated as the weighted average of time points, where weights are proportional to the values in the time series.
- Parameters:
data (pandas.Series) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
The temporal centroid of the time series, expressed as a timestamp.
- Return type:
pd.Timestamp
References
[1] Zauner, J., Hartmeyer, S., & Spitschan, M. (2025). LightLogR: Reproducible analysis of personal light exposure data. Journal of Open Source Software, 10(107), 7601. https://doi.org/10.21105/joss.07601. RRID:SCR_025408
Cosinor Analysis#
- class circstudio.analysis.cosinor.cosinor.Cosinor(fit_params=None)[source]#
Bases:
objectClass for Cosinor analysis. Cosinor analysis fits a cosine curve to a time series to summarize a rhythmic pattern using a small set of interpretable parameters.
- It answers questions like:
What is the typical baseline level of the signal? -> Mesor
How large is the rhythm around that baseline? -> Amplitude
When does the peak occur within the cycle? -> Acrophase
What cycle length best matches the data? -> Period
Model#
This implementation uses a standard 1-harmonic cosinor model:
y(x) = Mesor + Amplitude * cos(2π/Period * x + Acrophase)
where `x`is time expressed in sample units (e.g., minutes since start), not necessarily clock time.
Typical usage#
>>> model = Cosinor() >>> result = model.fit(series) >>> mesor = result.params['Mesor'].value >>> amplitude = result.params['Amplitude'].value >>> period = result.params['Period'].value >>> acrophase = result.params['Acrophase'].value >>> best = model.best_fit(series, result.params) >>> fig = model.plot(series, result.params)
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
[3] Cornelissen, G. (2014). Cosinor-based rhythmometry. Theoretical Biology and Medical Modelling, 11(1), 16. https://doi.org/10.1186/1742-4682-11-16
- best_fit(data, params)[source]#
Best fit function of the data.
- Parameters:
data (pandas.Series) – Originally fitted time series.
params (instance of Parameters [1]_) – Best fit parameters.
- Returns:
bestfit_data – Time series of the best fit data.
- Return type:
pandas.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
[3] Non-Linear Least-Squares Minimization and Curve-Fitting for Python. https://lmfit.github.io/lmfit-py/index.html
- fit(data, params=None, method='leastsq', nan_policy='raise', reduce_fcn=None, verbose=False)[source]#
Fit the actigraphy data using a cosinor function.
- Parameters:
data (pandas.Series) – Input time series.
params (instance of Parameters [1]_, optional.) – Initial fit parameters. If None, use the default parameters. Default is None.
method (str, optional) – Name of the fitting method to use [1]_. Default is ‘leastsq’.
nan_policy (str, optional) –
Specifies action if the objective function returns NaN values. One of:
’raise’: a ValueError is raised
’propagate’: the values returned from userfcn are un-altered
’omit’: non-finite values are filtered
Default is ‘raise’.
reduce_fcn (str, optional) –
Function to convert a residual array to a scalar value for the scalar minimizers. Optional values are:
’None’ : sum of squares of residual
’negentropy’ : neg entropy, using normal distribution
’neglogcauchy’: neg log likelihood, using Cauchy distribution
Default is None.
verbose (bool, optional) – If set to True, display fit informations. Default is False.
- Returns:
fit_results – Fit results.
- Return type:
MinimizerResult
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
[3] Non-Linear Least-Squares Minimization and Curve-Fitting for Python. https://lmfit.github.io/lmfit-py/index.html
Mathematical Models#
- class circstudio.analysis.models.math_models.Breslow13(data=None, inputs=None, time=None, h1_threshold=0.001, k=0.55, i0=9500.0, i1=100.0, alpha_0=0.1, beta=0.007, p=0.5, r=15.36, g=37.0, b=0.4, gamma=0.13, kappa=3.819718634205488, tauc=24.1, f=0.99729, m=7.0, eta=0.04, xi=0.54, beta_ip=2.8188, beta_cp=1.206, beta_ap=0.5832, a=3.75192, phi_on=-0.1701853071795858, phi_off=-1.931185307179586, delta=600.0, mmax=0.019513, hstat=861.0, sigma=50.0, phi_ref=0.97, cbt_to_dlmo=7.0, initial_condition=None)[source]#
Bases:
ModelBreslow et al. (2013) circadian model with explicit melatonin dynamics.
This model extends classical light-driven limit-cycle oscillator models of the human circadian pacemaker by incorporating a multi-compartment melatonin system. In addition to the core state variables (x, x_c, n), it models pineal, plasma, and exogenous melatonin concentrations.
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
State variables#
x : Core oscillator state variable x_c : Complementary oscillator variable (quadrature component) n : Phototransduction state h1 : Pineal melatonin concentration h2 : Plasma melatonin concentration h3 : Exogenous melatonin compartment
- h1_threshold#
Lower bound used to prevent negative pineal melatonin production.
- Type:
float
- tauc#
Intrinsic circadian period (hours).
- Type:
float
- phi_on#
Phase angle (radians) at which melatonin synthesis is activated.
- Type:
float
- phi_off#
Phase angle (radians) at which melatonin synthesis is deactivated.
- Type:
float
- phi_ref#
Phase offset (radians) used when converting internal oscillator phase to clock time (e.g., CBTmin timing).
- Type:
float
- cbt_to_dlmo#
Time offset (in hours) from CBTmin to DLMO.
- Type:
float
- initial_conditions#
State vector at the start of simulation (default: [-0.219, -1.22, 0.519, 0.0, 0.0, 0.0]).
- Type:
numpy.ndarray
- model_states#
Integrated state trajectories of the model.
- Type:
numpy.ndarray
- time#
Array of time points for simulation.
- Type:
numpy.ndarray
- inputs#
Array of input values (e.g., light intensity and wake) over time.
- Type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
References
[1] Breslow ER, Phillips AJ, Huang JM, St Hilaire MA, Klerman EB. A mathematical model of the circadian phase-shifting effects of exogenous melatonin. J Biol Rhythms. 2013 Feb;28(1):79-89. doi: 10.1177/0748730412468081. PMID: 23382594; PMCID: PMC3733227.
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Amplitude of the oscillator computed from the integrated state trajectory.
- Returns:
Amplitude at each time point: sqrt(x^2 + xc^2).
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the state variable x.
- Returns:
Array of time points (in hours) where minima of x occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- derivative(t, state, input)[source]#
Computes the derivatives of the state variables at a given time and light input.
- Parameters:
t (float) – Current simulation time (in hours).
state (numpy.ndarray) – Current values of the state variables at time t.
input (float) – Contains light intensity input (in lux) at time t and the corresponding wake state.
- Returns:
Derivatives at time t.
- Return type:
numpy.ndarray
- class circstudio.analysis.models.math_models.ESRI(data=None, time=None, inputs=None, window_size_days=4.0, esri_time_step_hours=1.0, initial_amplitude=0.1, midnight_phase=1.65238233)[source]#
Bases:
objectCompute the Entrainment Signal Regularity Index (ESRI) for a given light schedule.
The ESRI quantifies the strength and regularity of a light schedule by measuring how clustered the phases of a simulated circadian oscillator become after a fixed-duration exposure. A high ESRI indicates strong, regular entrainment (phases converge to a similar value), whereas a low ESRI indicates weak or irregular entrainment.
- The computation follows this procedure:
1. Slide a window of length window_size_days across the input time series in steps of esri_time_step_hours. 2. For each window start time, initialize a HannaySP model with a small amplitude and phase. 3. Simulate the oscillator under the window’s light input. 4. Record the final amplitude as the ESRI value for that window.
- Parameters:
time (array_like) – Time points (in hours) corresponding to the provided light intensities.
inputs (array_like) – Light intensity values (e.g., lux) at each time point.
window_size_days (float, optional) – Size of the sliding window in days over which ESRI is computed (default: 4.0).
esri_time_step_hours (float, optional) – Step size in hours for sliding the window (default: 1.0).
initial_amplitude (float, optional) – Initial amplitude for the HannaySP model; should be low to represent maximal phase dispersion (default: 0.1).
midnight_phase (float, optional) – Phase (in radians) corresponding to circadian midnight (default: 1.65238233).
- window_size#
Window length in days.
- Type:
float
- esri_time_step#
Step size in hours for sliding the window.
- Type:
float
- initial_amplitude#
Initial oscillator amplitude for each simulation.
- Type:
float
- midnight_phase#
Phase offset for circadian midnight (radians).
- Type:
float
- time_vector#
Time points (hours) used for ESRI calculation.
- Type:
ndarray
- light_vector#
Light intensity values corresponding to time_vector.
- Type:
ndarray
- raw_values#
DataFrame indexed by window start time (hours) with column esri for computed values.
- Type:
pandas.DataFrame
- mean#
Mean ESRI value across all windows.
- Type:
float
- std#
Standard deviation of ESRI values across all windows.
- Type:
float
- class circstudio.analysis.models.math_models.Forger(data=None, inputs=None, time=None, taux=24.2, mu=0.23, g=33.75, alpha_0=0.05, beta=0.0075, p=0.5, i0=9500.0, k=0.55, cbt_to_dlmo=7.0, initial_condition=None, hilaire_correction=False)[source]#
Bases:
ModelImplements the mathematical model of human circadian rhythms developed by Forger, Jewett and Kronauer [1]. The formalism includes a representation of the biochemical conversion of the light signal into a drive on the circadian pacemaker, which is modeled as a van der Pol oscillator. This cubic model is characterized by three state variables: x, xc and n. While n can be interpreted as the proportion of activated photoreceptors, at a given time, x and xc cannot directly be mapped to specific physiological mechanisms. Instead, x and xc are used to predict biologically meaningful quantities, such as the core body temperature minimum (CBTmin).
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
- taux#
Intrinsic period of the oscillator (hours).
- Type:
float
- mu#
stiffness of the van der Pol oscillator.
- Type:
float
- g#
Light sensitivity scaling parameter.
- Type:
float
- alpha_0#
Baseline forward rate constant governing the photon-driven activation (or depletion) of photoreceptors. This parameter scales the rate at which incident light converts available photoreceptors into an active or “used” state.
- Type:
float
- beta#
Backward rate constant governing photoreceptor recovery or regeneration. This parameter controls the rate at which used photoreceptors return to the available state, representing dark adaptation or biochemical recovery processes.
- Type:
float
- p#
Power-law exponent for light-dependent photoreceptor activation. This parameter determines how sensitively the forward rate constant α scales with light intensity.
- Type:
float
- i0#
Reference light intensity used to normalize the input light intensity vector I.
- Type:
float
- k#
Coupling coefficient scaling the influence of the photic drive B on the circadian pacemaker. It modulates the sensitivity of the oscillator to light.
- Type:
float
- cbt_to_dlmo#
Time offset (in hours) from CBTmin to DLMO.
- Type:
float
- initial_conditions#
State vector at the start of simulation (default: [-0.0843259, -1.09607546, 0.45584306]).
- Type:
numpy.ndarray
- model_states#
Integrated state trajectories of the model.
- Type:
numpy.ndarray
- time#
Array of time points for simulation.
- Type:
numpy.ndarray
- inputs#
Array of input values (e.g., light intensity) over time.
- Type:
numpy.ndarray
- hilaire_correction#
Whether to use Hilaire’s formula to compute alpha. Default is False.
- Type:
bool
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
References
[1] Forger DB, Jewett ME, Kronauer RE. A Simpler Model of the Human Circadian Pacemaker. Journal of Biological Rhythms. 1999;14(6):533-538. doi:10.1177/074873099129000867
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Amplitude of the oscillator computed from the integrated state trajectory.
- Returns:
Amplitude at each time point: sqrt(x^2 + xc^2).
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the state variable x.
- Returns:
Array of time points (in hours) where minima of x occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
- Parameters:
t (float) – Current simulation time (in hours).
state (numpy.ndarray) – Current values of the state variables at time t.
light (float) – Light intensity input (in lux) at time t.
- Returns:
Derivatives at time t.
- Return type:
numpy.ndarray
- class circstudio.analysis.models.math_models.HannaySP(data=None, inputs=None, time=None, tau=23.84, k=0.06358, gamma=0.024, beta=-0.09318, a1=0.3855, a2=0.1977, betal1=-0.0026, betal2=-0.957756, sigma=0.0400692, g=33.75, alpha_0=0.05, delta=0.0075, p=1.5, i0=9325.0, cbt_to_dlmo=7.0, initial_condition=None)[source]#
Bases:
ModelImplements the Hannay Single-Population (SP) model of human circadian rhythms [1]. It describes a population of weakly-coupled oscillators using a formalism with three state variables: R (collective amplitude), Psi (collective phase), and n (proportion of light receptors used). In contrast to the FJK formalism, all three state variables are directly biologically interpretable. The model is derived from the mathematical description of the rhythm within individual cells in the suprachiasmatic nucleus (SCN) of the hypothalamus, from which a coherent behavior emerges.
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
- tau#
Intrinsic period of the oscillator (hours).
- Type:
float
- k#
Average coupling strength between clock neurons.
- Type:
float
- gamma#
Width (dispersion) of the intrinsic frequency distribution across the population of clock neurons, reflecting variability between neurons.
- Type:
float
- beta#
Backward rate constant governing photoreceptor recovery or regeneration. This parameter controls the rate at which used photoreceptors return to the available state, representing dark adaptation or biochemical recovery processes.
- Type:
float
- a1#
Coefficient that scales the first harmonic component of the single-cell phase-response curve
- Type:
float
- a2#
Coefficient that scales the first harmonic component of the single-cell phase-response curve
- Type:
float
- betal1#
Phase offset for first harmonic component of the single-cell phase-response curve (radians).
- Type:
float
- betal2#
Phase offset for second harmonic component of the single-cell phase-response curve (radians).
- Type:
float
- sigma#
Factor scaling the effect of light input on the circadian pacemaker (B(t)).
- Type:
float
- g#
Light sensitivity scaling parameter.
- Type:
float
- alpha_0#
Baseline forward rate constant governing the photon-driven activation (or depletion) of photoreceptors. This parameter scales the rate at which incident light converts available photoreceptors into an active or “used” state.
- Type:
float
- delta#
Backward rate constant governing photoreceptor recovery or regeneration. This parameter controls the rate at which used photoreceptors return to the available state, representing dark adaptation or biochemical recovery processes.
- Type:
float
- p#
Power-law exponent for light-dependent photoreceptor activation. This parameter determines how sensitively the forward rate constant α scales with light intensity.
- Type:
float
- i0#
Reference light intensity used to normalize the input light intensity vector I.
- Type:
float
- cbt_to_dlmo#
Time offset (in hours) from CBTmin to DLMO.
- Type:
float
- initial_conditions#
State vector at the start of simulation (default: [0.82041911, 1.71383697, 0.52318122]).
- Type:
numpy.ndarray
- model_states#
Integrated state trajectories of the model.
- Type:
numpy.ndarray
- time#
Array of time points for simulation.
- Type:
numpy.ndarray
- inputs#
Array of input values (e.g., light intensity) over time.
- Type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
References
[1] Hannay KM, Booth V, Forger DB. Macroscopic Models for Human Circadian Rhythms. Journal of Biological Rhythms. 2019;34(6):658-671. https://doi.org/10.1177/0748730419878298
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Collective rhythm amplitude (R) of the oscillator population.
- Returns:
Amplitude (R) at each time point.
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the collective phase trajectory.
- Returns:
Array of time points (in hours) where minima of cos(Psi) occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
- Parameters:
t (float) – Current simulation time (in hours).
state (numpy.ndarray) – Current values of the state variables at time t.
light (float) – Light intensity input (in lux) at time t.
- Returns:
Derivatives at time t.
- Return type:
numpy.ndarray
- class circstudio.analysis.models.math_models.HannayTP(data=None, inputs=None, time=None, tauv=24.25, taud=24.0, kvv=0.05, kdd=0.04, kvd=0.05, kdv=0.01, gamma=0.024, a1=0.440068, a2=0.159136, betal=0.06452, betal2=-1.38935, sigma=0.0477375, g=33.75, alpha_0=0.05, delta=0.0075, p=1.5, i0=9325.0, cbt_to_dlmo=7.0, initial_condition=None)[source]#
Bases:
ModelImplements the Hannay Two-Population (TP) model of human circadian rhythms [1]. The neuroanatomy of the suprachiasmatic nucleus (SCN) in the hypothalamus distinguishes two primary populations: the ventral cluster, which receives most light input, and the dorsal cluster. To better reflect this neurophysiological organization, Hannay et al. extended the Single Population (SP) model to explicitly represent both the ventral and dorsal groups, resulting in the TP model. Similar to the HannaySP, all five state variables are directly biologically interpretable. The model is also derived from the mathematical description of the rhythm within individual cells, from which a coherent behavior emerges.
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
- tauv#
Intrinsic period of the ventral oscillator (hours).
- Type:
float
- taud#
Intrinsic period of the dorsal oscillator (hours).
- Type:
float
- kvv#
Average coupling strength within the ventral oscillator population.
- Type:
float
- kdd#
Average coupling strength within the dorsal oscillator population.
- Type:
float
- kvd#
Average strength from ventral to dorsal population.
- Type:
float
- kdv#
Average strength from dorsal to ventral population.
- Type:
float
- gamma#
Width (dispersion) of the intrinsic frequency distribution across the population of clock neurons, reflecting variability between neurons.
- Type:
float
- a1#
Coefficient that scales the first harmonic component of the single-cell phase-response curve
- Type:
float
- a2#
Coefficient that scales the first harmonic component of the single-cell phase-response curve
- Type:
float
- betal1#
Phase offset for first harmonic component of the single-cell phase-response curve (radians).
- Type:
float
- betal2#
Phase offset for second harmonic component of the single-cell phase-response curve (radians).
- Type:
float
- sigma#
Factor scaling the effect of light input on the circadian pacemaker (B(t)).
- Type:
float
- g#
Light sensitivity scaling parameter.
- Type:
float
- alpha_0#
Baseline forward rate constant governing the photon-driven activation (or depletion) of photoreceptors. This parameter scales the rate at which incident light converts available photoreceptors into an active or “used” state.
- Type:
float
- delta#
Backward rate constant governing photoreceptor recovery or regeneration. This parameter controls the rate at which used photoreceptors return to the available state, representing dark adaptation or biochemical recovery processes.
- Type:
float
- p#
Power-law exponent for light-dependent photoreceptor activation. This parameter determines how sensitively the forward rate constant α scales with light intensity.
- Type:
float
- i0#
Reference light intensity used to normalize the input light intensity vector I.
- Type:
float
- cbt_to_dlmo#
Time offset (in hours) from CBTmin to DLMO.
- Type:
float
- initial_conditions#
State vector at the start of simulation (default: [0.82423745, 0.82304996, 1.75233424, 1.863457, 0.52318122]).
- Type:
numpy.ndarray
- model_states#
Integrated state trajectories of the model.
- Type:
numpy.ndarray
- time#
Array of time points for simulation.
- Type:
numpy.ndarray
- inputs#
Array of input values (e.g., light intensity) over time.
- Type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
- cbt()[source]#
Identifies the timing of core body temperature minima based on the ventral phase trajectory.
References
[1] Hannay KM, Booth V, Forger DB. Macroscopic Models for Human Circadian Rhythms. Journal of Biological Rhythms. 2019;34(6):658-671. https://doi.org/10.1177/0748730419878298
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Collective ventral rhythm amplitude (Rv) of the oscillator population.
- Returns:
Amplitude Rv at each time point.
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the ventral phase trajectory.
- Returns:
Array of time points (in hours) where minima of cos(Psiv) occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
- Parameters:
t (float) – Current simulation time (in hours).
state (numpy.ndarray) – Current values of the state variables at time t.
light (float) – Light intensity input (in lux) at time t.
- Returns:
Derivatives at time t.
- Return type:
numpy.ndarray
- class circstudio.analysis.models.math_models.Hilaire07(data=None, sleep_algo='Roenneberg', inputs=None, time=None, taux=24.2, g=37.0, k=0.55, mu=0.13, beta=0.007, q=0.3333333333333333, rho=0.032, i0=9500.0, p=0.5, a0=0.1, phi_xcx=-2.98, phi_ref=0.97, cbt_to_dlmo=7.0, initial_condition=None)[source]#
Bases:
ModelSt. Hilaire et al. (2007) human circadian pacemaker model.
This model extends earlier light-driven circadian oscillator models (e.g., Kronauer / Forger formulations) by including a non-photic component representing behavioral modulation (sleep/wake state).
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
Model inputs#
The system is driven by: - Light intensity (lux) - Sleep/rest stat (binary; 1=sleep/rest, 0=wake)
Sleep state may be computed automatically from actigraphy data using one of the supported sleep scoring algorithms available in circStudio (e.g., Cole-Kripke, Roenneberg), or supplied directly by the user.
- param data:
Time-indexed light data. Required if inputs and time are not explicitly provided.
- type data:
pandas.Series, optional
- param sleep_algo:
Sleep scoring algorithm to use (default: “Roenneberg”). Alternatively, a precomputed binary sleep series may be supplied.
- type sleep_algo:
str or pandas.Series, optional
- param inputs:
Light input.
- type inputs:
array-like, optional
- param time:
Time input.
- type time:
array-like, optional
- param taux:
Intrinsic circadian period (hours).
- type taux:
float
- param g:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type g:
float
- param k:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type k:
float
- param mu:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type mu:
float
- param beta:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type beta:
float
- param q:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type q:
float
- param rho:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type rho:
float
- param i0:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type i0:
float
- param p:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type p:
float
- param a0:
Model parameters governing light response, non-photic drive, and oscillator dynamics.
- type a0:
float
- param phi_xcx:
Polar phase angle (radians) between the state variables x and x_c.
- type phi_xcx:
float
- param phi_ref:
Fixed phase offset (radians) used to convert internal oscillator phase to clock time.
- type phi_ref:
float
- param cbt_to_dlmo:
Phase relationship between CBT minimum and DLMO (hours).
- type cbt_to_dlmo:
float
- param initial_condition:
Initial state vector [-0.0480751, -1.22504441, 0.51854818].
- type initial_condition:
array-like, optional
References
- [1] St. Hilaire, M. A., Klerman, E. B., Khalsa, S. B. S., Wright, K. P., Czeisler, C. A., & Kronauer, R. E. (2007).
Addition of a non-photic component to a light-based mathematical model of the human circadian pacemaker. Journal of Theoretical Biology, 247(4), 583–599. https://doi.org/10.1016/j.jtbi.2007.04.001
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Amplitude of the oscillator computed from the integrated state trajectory.
- Returns:
Amplitude at each time point: sqrt(x^2 + xc^2).
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the state variable x.
- Returns:
Array of time points (in hours) where minima of x occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- derivative(t, state, input)[source]#
Computes the derivatives of the state variables at a given time, sleep and light input.
- Parameters:
t (float) – Current simulation time (in hours).
state (numpy.ndarray) – Current values of the state variables at time t.
input (tuple) – Contains light intensity input (in lux) at time t and the corresponding wake state.
- Returns:
Derivatives at time t.
- Return type:
numpy.ndarray
- phase()[source]#
Returns the phase angle of the oscillator computed from the integrated state trajectory.
- Returns:
Phase angle (radians) at each time point: arctangent(xc/x).
- Return type:
numpy.ndarray
- sleep_vector(algo='Roenneberg', **kwargs)[source]#
Return a binary sleep/rest series align to self.data.
- This method either:
Runs one of circStudio’s supported sleep-detection algorithms
on self.data or * Returns a user-supplied sleep series directly.
The output is always a pandas Series indexed by the same DatetimeIndex as the input data (or by the inex of the user-supplied series).
- Parameters:
algo (str or pandas.Series, optional) –
Sleep scoring method to use or pandas Series to use as sleep vector - If a string, must be one of:
{“Roenneberg”, “Crespo”, “Oakley”, “Scripps”, “Sadeh”, “Cole_Kripke”}.
If a pandas Series, it is assumed to already represent a sleep/rest vector (binary) and is returned unchanged. This is useful when the user has computed sleep elsewhere or wants full control
kwargs – Additional keyword arguments passed through the selected algorithm. For example, you can override algorithm default parameters such as thresholds, windows, or rescoring options.
- Returns:
Binary sleep/rest classification time series.
Convention: values are expected to encode sleep/rest as 1 and wake as 0. If an external algorithm uses the opposite convention, convert it before passing it here.
- Return type:
pandas.Series
- Raises:
ValueError – If self.data is not indexed by a DatetimeIndex (needed to infer the sampling interval), or if algo is an unknown algorithm.
- class circstudio.analysis.models.math_models.Jewett(data=None, inputs=None, time=None, taux=24.2, mu=0.13, g=19.875, beta=0.013, k=0.55, q=0.3333333333333333, i0=9500, p=0.6, alpha_0=0.16, phi_ref=0.8, cbt_to_dlmo=7.0, initial_condition=None)[source]#
Bases:
ModelImplements a refined version of the Forger, Jewett and Kronauer (FJK) model of human circadian rhythms, containing a nonlinearity of degree seven [1]. Compared to the FJK model implemented in the Forger subclass, the revised model recovers strength more slowly when the rhythm is very weak (low amplitude), but recovers faster once it is close to a stable rhythm (high amplitude).
This model is characterized by three state variables: x, xc and n. While n can be interpreted as the proportion of activated photoreceptors, at a given time, x and xc cannot directly be mapped to specific physiological mechanisms. Instead, x and xc are used to predict biologically meaningful quantities, such as the core body temperature minimum (CBTmin).
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
- taux#
Intrinsic period of the oscillator (hours).
- Type:
float
- mu#
Stiffness of the van der Pol oscillator.
- Type:
float
- g#
Light sensitivity scaling parameter.
- Type:
float
- alpha_0#
Baseline forward rate constant governing the photon-driven activation (or depletion) of photoreceptors. This parameter scales the rate at which incident light converts available photoreceptors into an active or “used” state.
- Type:
float
- beta#
Backward rate constant governing photoreceptor recovery or regeneration. This parameter controls the rate at which used photoreceptors return to the available state, representing dark adaptation or biochemical recovery processes.
- Type:
float
- p#
Power-law exponent for light-dependent photoreceptor activation. This parameter determines how sensitively the forward rate constant α scales with light intensity.
- Type:
float
- i0#
Reference light intensity used to normalize the input light intensity vector I.
- Type:
float
- k#
Coupling coefficient scaling the influence of the photic drive B on the circadian pacemaker. It modulates the sensitivity of the oscillator to light.
- Type:
float
- q#
Coefficient governing an additional effect of light whereby, while light is present, it acts to shorten the intrinsic period of the pacemaker in addition to shifting its phase and amplitude.
- Type:
float
- phi_ref#
Reference phase offset relating the timing of the model state minimum (x_min) to the timing of core body temperature minimum (CBT_min).
- Type:
float
- cbt_to_dlmo#
Time offset (in hours) from CBTmin to DLMO.
- Type:
float
- initial_conditions#
State vector at the start of simulation (default: [-0.10097101, -1.21985662, 0.50529415]).
- Type:
numpy.ndarray
- model_states#
Integrated state trajectories of the model.
- Type:
numpy.ndarray
- time#
Array of time points for simulation.
- Type:
numpy.ndarray
- inputs#
Array of input values (e.g., light intensity) over time.
- Type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
References
[1] Jewett ME, Forger DB, Kronauer RE. Revised Limit Cycle Oscillator Model of Human Circadian Pacemaker. Journal of Biological Rhythms. 1999;14(6):493-500. https://doi.org/10.1177/074873049901400608
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Amplitude of the oscillator computed from the integrated state trajectory.
- Returns:
Amplitude at each time point: sqrt(x^2 + xc^2).
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the state variable x.
- Returns:
Array of time points (in hours) where minima of x occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- derivative(t, state, light)[source]#
Computes the derivatives of the state variables at a given time and light input.
- Parameters:
t (float) – Current simulation time (in hours).
state (numpy.ndarray) – Current values of the state variables at time t.
light (float) – Light intensity input (in lux) at time t.
- Returns:
Derivatives at time t.
- Return type:
numpy.ndarray
- class circstudio.analysis.models.math_models.Model(initial_conditions, data=None, time=None, inputs=None)[source]#
Bases:
objectNumerically integrates a system of ordinary differential equations (ODEs), whose evolution may depend on external inputs (e.g., light) and initial conditions. Time points and input data are either provided directly or extracted from a pandas.Series with a DatetimeIndex.
- initial_conditions#
Array of initial conditions for the model states.
- Type:
numpy.ndarray
- model_states#
Array containing the model state trajectories after integration.
- Type:
numpy.ndarray or None
- data#
Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., light intensity). Time and value arrays are extracted from this series.
- Type:
pandas.Series, optional
- time#
Array of time points (in hours); must be monotonically increasing.
- Type:
numpy.ndarray, optional
- inputs#
Array of input values (e.g., light intensity) corresponding to each time point.
- Type:
numpy.ndarray, optional
- dlmos()[source]#
Calculates the predicted Dim Light Melatonin Onset (DLMO) time points using a fixed, pre-specified offset (default: seven hours).
- Returns:
Array of time points (in hours) at which DLMO is expected to occur.
- Return type:
numpy.ndarray
- get_initial_conditions(loop_number, data=None, light_vector=None, time_vector=None)[source]#
Attempts to equilibrate the model’s initial conditions by repeated simulation given a light and time vector.
- This method iteratively integrates the model for a user-specified number of cycles to assess whether equilibrium
is achieved, as indicated by the stabilization of the predicted DLMO (Dim Light Melatonin Onset).
- Parameters:
(int) (loop_number) – Number of consecutive simulation cycles performed to assess whether the state trajectory of the circadian system’s state variables converges to equilibrium under the given input conditions.
(pandas.Series (data) – Input data series with a DatetimeIndex. The index represents time points and the values represent input data (e.g., light intensity). The time and input arrays are extracted from this series.
optional) – Input data series with a DatetimeIndex. The index represents time points and the values represent input data (e.g., light intensity). The time and input arrays are extracted from this series.
(numpy.ndarray (time_vector) – Array of input values (typically, light intensity).
optional) – Array of input values (typically, light intensity).
(numpy.ndarray – Array of time points (typically, time in hours).
optional) – Array of time points (typically, time in hours).
- Returns:
The final state of the model after attempting to reach equilibrium (either an equilibrated solution or last simulated state).
- Return type:
numpy.ndarray
- initialize_model_states()[source]#
Initializes the model states by numerically integrating the system equations.
This method runs the model integration using the current initial conditions, input values, and time vector, and stores the result in self.model_states.
- integrate(light_vector=None, time_vector=None, initial_condition=None)[source]#
Numerically integrates a system of ordinary differential equations (ODEs).
This method uses SciPy odeint function to simulate the model dynamics over time, given a set of initial conditions and external inputs (e.g., light intensity). By default, it uses the class attributes self.inputs, self.time, and self.initial_condition, but alternative arrays can be provided.
The input and time vectors must be of the same length, and the system’s equations must be defined by the `derivative`method (which should be implemented within subclass of the Model class).
- Parameters:
(numpy.ndarray (initial_condition) – Array of input values (typically, light intensity).
optional) – Array of input values (typically, light intensity).
(numpy.ndarray – Array of time points (typically, time in hours).
optional) – Array of time points (typically, time in hours).
(numpy.ndarray – Array of initial conditions.
optional) – Array of initial conditions.
- Returns:
Simulated state trajectories over the specified time vector.
- Return type:
numpy.ndarray
- class circstudio.analysis.models.math_models.ModelComparer(data=None, inputs=None, time=None, equilibrate=False, loop_number=10, hilaire_correction=True, a1=1.0, a2=1.0, p1=1.0, p2=1.0, m1=0.0, m2=0.0)[source]#
Bases:
objectFramework for mapping state variables between circadian rhythm models.
The ModelComparer provides a framework for relating the state variables of the Forger model to the state variables of the HannaySP model. It enables a direct comparison between the two models and facilitates a more interpretable, physiologically grounded understanding of the Forger model states by expressing them as functions of the circadian phase predicted by the HannaySP model.
- Parameters:
data (pandas.Series or pandas.DataFrame, optional) – Time-indexed light exposure data. If provided, the time vector is inferred from the index (in hours since the first sample), and the light input is taken from the values.
inputs (array-like, optional) – Light input time series. Must be provided together with time if data is not supplied.
time (array-like, optional) – Time vector (in hours). Must be provided together with inputs if data is not supplied.
equilibrate (bool, default False) – If True, both models are equilibrated prior to simulation by repeatedly looping the input light profile to estimate stable initial conditions.
loop_number (int, default 10) – Number of light-profile repetitions used during equilibration.
a1 (float, default 1.0) – Amplitude parameters for the trigonometric mapping of the Forger state variables.
a2 (float, default 1.0) – Amplitude parameters for the trigonometric mapping of the Forger state variables.
p1 (float, default 1.0) – Phase scaling parameters for the trigonometric mapping.
p2 (float, default 1.0) – Phase scaling parameters for the trigonometric mapping.
m1 (float, default 0.0) – Offset parameters for the trigonometric mapping.
m2 (float, default 0.0) – Offset parameters for the trigonometric mapping.
- time_vector#
Time vector (hours).
- Type:
ndarray
- light_vector#
Light input time series.
- Type:
ndarray
- x, xc
State variables of the Forger model.
- Type:
ndarray
- phase_vector#
Collective phase of the HannaySP model.
- Type:
ndarray
- predicted_x, predicted_xc
Predicted Forger state variables obtained from the HannaySP phase.
- Type:
ndarray or None
- cumulative_rmse()[source]#
Compute cumulative RMSE for the predicted Forger model states.
- Returns:
crmse_x (ndarray) – Cumulative RMSE between observed and predicted x.
crmse_xc (ndarray) – Cumulative RMSE for state variable xc.
Notes
Useful for assessing how prediction error evolves over time. Requires predicted values to be available.
- find_optimal_params(change_params=True)[source]#
Estimate the optimal mapping parameters between HannaySP and Forger states.
Uses non-linear least squares regression to estimate amplitude, offset, and phase-scaling parameters for the mapping between the HannaySP phase and the Forger model state variables x and xc.
- Parameters:
change_params (bool, default True) – If True, updates the mapping parameters stored in the object.
- Returns:
params – Estimated parameters for x and xc mappings: [[a1, m1, p1], [a2, m2, p2]]
- Return type:
ndarray, shape (2, 3)
- half_life_crmse()[source]#
Fit an exponential decay function to the cumulative RMSE curves and compute the half life times of the RMSE for both the x and xc values.
The half-life represents the time required for the prediction error to decrease by 50%, and can be used as an index of how readily a given light schedule entrains the circadian pacemaker.
- Returns:
half_life_x (float) – Half-decay time for the x state variable.
half_life_xc (float) – Half-decay time for the xc state variable.
- linearize_phase(change_params=False)[source]#
Linearize the phase of the Forger model state variables.
Fits a first-degree polynomial to the phase trajectory of the HannaySP and optionally replaces the stored phase vector with its linear approximation.
- Parameters:
change_params (bool, default False) – If True, replaces phase_vector with the linearized phase.
- Returns:
linear_phase – Linear approximation of the collective phase.
- Return type:
ndarray
- predict_forger(change_params=True)[source]#
Predict Forger state variables using the collective phase predicted by the HannaySP model.
Expresses the Forger state variables (x, xc) as explicit functions of the collective phase predicted by the HannaySP model.
- Parameters:
change_params (bool, default True)
True (If)
variables (stores the predicted values for the x and xc state)
predicted_xc. (in the attributes predicted_x and)
- Returns:
predicted_x (ndarray) – Predicted values of the Forger model state variable x
predicted_xc (ndarray) – Predicted values of the Forger model state variable xc
- class circstudio.analysis.models.math_models.Skeldon23(data=None, inputs=None, time=None, mu=17.78, chi=45.0, h0=13.0, delta=1.0, ca=1.72, tauc=24.2, f=0.99669, g=19.9, p=0.6, k=0.55, b=0.4, gamma=0.23, alpha_0=0.16, beta=0.013, i0=9500.0, kappa=3.819718634205488, c20=0.7896, alpha21=-0.3912, alpha22=0.7583, beta21=-0.4442, beta22=0.025, beta23=-0.9647, s0=0.0, forced_wakeup_light_threshold=None, forced_wakeup_weekday_only=False, cbt_to_dlmo=7.0, initial_condition=array([0.23995682, -1.1547196, 0.50529415, 12.83846474]))[source]#
Bases:
objectSkeldon et al. (2023) model. It simulates circadian phase and sleep/wake patterns from a light time series.
- This model takes a light exposure (lux over time) and simulates:
A circadian rhythm signal (internal clock dynamics)
A sleep-pressure signal (builds up during wake, dissipates during sleep)
A predicted sleep/wake state (wake=0, sleep=1).
The user does not need to provide a sleep series. The model generates sleep/wake internally by applying a switching rule based on sleep pressure and circadian timing.
Our implementation closely follows the approach of the circadian`package by Arcascope [2]. However, we use the more powerful LSODA integrator (via SciPy’s `odeint) for numerical integration, enabling the integration of the system using more complex light trajectories.
- data#
Time-indexed light intensity series (lux) with a DatetimeIndex.
- Type:
pandas.Series, optional
- forced_wakeup_weekday_only#
If True, apply forced wake-up only on weekdays according to the author’s rule.
- Type:
bool, optional
- forced_wakeup_light_threshold#
If provided, forces wake (s=0) whenever light exceeds this threshold.
- Type:
float or None, optional
- mu, chi, h0, delta, ca
Sleep homeostasis and switching parameters.
- Type:
float
- tauc, f, g, p, k, b, gamma, alpha_0, beta, i0, kappa
Circadian oscillator and phototransduction parameters. Light is transformed into a photic drive via alpha(light), then b(t).
- Type:
float
- c20, alpha21, alpha22, beta21, beta22, beta23
Parameters for circadian modulation term C(x, x_c) that shifts sleep thresholds.
- Type:
float
- s0#
Initial sleep state (0 = wake, 1 = sleep). Default is 0.
- Type:
float, optional
- cbt_to_dlmo#
Time offset (in hours) from CBTmin to DLMO.
- Type:
float
- initial_conditions#
State vector at the start of simulation (default: [0.23995682, -1.1547196, 0.50529415, 12.83846474]).
- Type:
numpy.ndarray
- model_states#
Integrated state trajectories of the model.
- Type:
numpy.ndarray
- time#
Array of time points for simulation.
- Type:
numpy.ndarray
- inputs#
Array of input values (e.g., light intensity) over time.
- Type:
numpy.ndarray
- derivative(t, state, light)#
Computes the derivatives of the state variables at a given time and light input.
References
[1] Skeldon, A. C., Garcia, T. R., Cleator, S. F., Monica, C. della, Ravindran, K. K. G., Revell, V. L., & Dijk, D.-J. (2023). Method to determine whether sleep phenotypes are driven by endogenous circadian rhythms or environmental light by combining longitudinal data and personalised mathematical models. PLOS Computational Biology, 19(12), e1011743. https://doi.org/10.1371/journal.pcbi.1011743
[2] Tavella, F., Hannay, K., & Walch, O. (2023). Arcascope/circadian: Refactoring of readers and metrics modules, Zenodo, v1.0.2. https://doi.org/10.5281/zenodo.8206871
- amplitude()[source]#
Amplitude of the oscillator computed from the integrated state trajectory.
- Returns:
Amplitude at each time point: sqrt(x^2 + xc^2).
- Return type:
numpy.ndarray
- cbt()[source]#
Time points corresponding to the predicted core bod temperature minima (CBTmin), derived from the state variable x.
- Returns:
Array of time points (in hours) where minima of x occur, corresponding to the CBTmin.
- Return type:
numpy.ndarray
- dlmos()[source]#
Calculates the predicted Dim Light Melatonin Onset (DLMO) time points using a fixed, pre-specified offset (default: seven hours).
- Returns:
Array of time points (in hours) at which DLMO is expected to occur.
- Return type:
numpy.ndarray
- get_initial_conditions(loop_number, data=None, light_vector=None, time_vector=None)[source]#
Attempts to equilibrate the model’s initial conditions by repeated simulation.
Works with the piecewise odeint integrator that returns: (time_hours, state_trajectory, sleep_state_trajectory)
- Returns:
Final continuous state [x, xc, n, h] after entrainment attempt.
- Return type:
np.ndarray
- integrate_piecewise_odeint(initial_state=None)[source]#
Integrate the Skeldon23 sleep/circadian model over time.
- This model contains:
Continuous variables (circadian + sleep pressure)
A discrete sleep state (awake=0, asleep=1)
- Because sleep state is discrete, we:
Keep sleep state fixed within each time interval
Integrate the continuous equations across that interval
Update sleep state at the end of the interval
- Returns:
time_hours (np.ndarray) – Time values in hours.
state_trajectory (np.ndarray) – Continuous state history [x, xc, n, h].
sleep_state_history (np.ndarray) – Sleep/wake state over time (0=wake, 1=sleep).
Sleep Scoring and Diary#
- circstudio.analysis.sleep.sleep.AoffT(data, whs=12)[source]#
Activity offset time.
Activity offset time derived from the daily activity profile.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
whs (int, optional) – Window half size. Default is 12.
- Returns:
aot – Activity offset time.
- Return type:
Timedelta
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.AonT(data, whs=12)[source]#
Activity onset time.
Activity onset time derived from the daily activity profile.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
whs (int, optional) – Window half size. Default is 12.
- Returns:
aot – Activity onset time.
- Return type:
Timedelta
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.CSM(ZCMn, settings='auto', score_rest=2, score_sleep=1, binarize=False)[source]#
Condor Sleep Model
Sleep-wake scoring algorithm developed by Condor Instrument for their ActTrust devices.
This algorithm works in a two-step fashion. First, it classifies all epochs as wake or rest, as function of each epoch’s score. Second, using a more stringent scoring threshold, “rest” epoch are re-classified as “sleep”. A relabelling mechanism using the labels of the surrounding epochs is also applied to consolidate periods of epochs labelled as rest or sleep.
- Parameters:
ZCMn (pandas.Series, optional) – Input data series with a DatetimeIndex that contains data from the ZCMn mode in ATR devices.
settings (str, optional) –
Parameter settings for the CSM algorithm. Refers to the data acquisition frequency. Available values are: * “auto”: use input data frequency. * “30s”: set parameters to optimal values obtained for a 30s data
acquisition frequency.
”60s”: set parameters to optimal values obtained for a 60s data acquisition frequency.
Default is ‘auto’.
score_rest (int, optional) – State index for epochs labelled as “rest”. Default is 2.
score_sleep (int, optional) – State index for epochs labelled as “sleep”. Default is 1.
binarize (bool, optional.) – If set to True, the state index is set to 1 if the epoch is labelled as sleep and 0 otherwise. Defautl is False.
- Returns:
csm – Series of state indices.
- Return type:
pandas.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Cole_Kripke(data, settings=None, threshold=1.0, rescoring=True)[source]#
Cole&Kripke algorithm for sleep-wake identification.
Algorithm for automatic sleep scoring based on wrist activity, developped by Cole, Kripke et al [1]_.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
settings (str, optional) –
Data reduction settings for which the optimal parameters have been derived. Available settings are:
”mean”: mean activity per minute
”10sec_max_overlap”: maximum 10-second overlapping epoch per minute
”10sec_max_non_overlap”: maximum 10-second nonoverlapping epoch per minute
”30sec_max_non_overlap”: maximum 30-second nonoverlapping epoch per minute
Default is “30sec_max_non_overlap”.
threshold (float, optional) – Threshold value for scoring sleep/wake. Default is 1.0.
rescoring (bool, optional) – If set to True, Webster’s rescoring rules are applied [2]_. Default is True.
- Returns:
ck – Time series containing the D scores (1: sleep, 0: wake) for each epoch.
- Return type:
pandas.core.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] 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–469. http://doi.org/10.1093/sleep/15.5.461
[2] Webster, J. B., Kripke, D. F., Messin, S., Mullaney, D. J., & Wyborney, G. (1982). An Activity-Based Sleep Monitor System for Ambulatory Use. Sleep, 5(4), 389–399. https://doi.org/10.1093/sleep/5.4.389
[3] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Crespo(data, frequency, zeta=15, zeta_r=30, zeta_a=2, t=0.33, alpha='8h', beta='1h', estimate_zeta=False, seq_length_max=100, verbose=False, plot=False)[source]#
Crespo algorithm for activity/rest identification.
Algorithm for automatic identification of activity-rest periods based on actigraphy, developed by Crespo et al. [1].
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
frequency (int) – Sampling frequency of the actigraphy trace.
zeta (int, optional) – Maximum number of consecutive zeroes considered valid. Default is 15.
zeta_r (int, optional) – Maximum number of consecutive zeroes considered valid (rest). Default is 30.
zeta_a (int, optional) – Maximum number of consecutive zeroes considered valid (active). Default is 2.
t (float, optional) – Percentile for invalid zeroes. Default is 0.33.
alpha (str, optional) – Average hours of sleep per night. Default is ‘8h’.
beta (str, optional) – Length of the padding sequence used during the processing. Default is ‘1h’.
estimate_zeta (bool, optional) – If set to True, zeta values are estimated from the distribution of ratios of the number of series of consecutive zeroes to the number of series randomly chosen from the actigraphy data. Default is False.
seq_length_max (int, optional) – Maximal length of the aforementioned random series. Default is 100.
verbose (bool, optional) – If set to True, print the estimated values of zeta. Default is False.
plot (bool, optional)
- Returns:
crespo – Time series containing the estimated periods of rest (1) and activity (0).
- Return type:
pandas.core.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Crespo, C., Aboy, M., Fernández, J. R., & Mojón, A. (2012). Automatic identification of activity–rest periods based on actigraphy. Medical & Biological Engineering & Computing, 50(4), 329–340. http://doi.org/10.1007/s11517-012-0875-y
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Crespo_AoT(data, frequency, zeta=15, zeta_r=30, zeta_a=2, t=0.33, alpha='8h', beta='1h', estimate_zeta=False, seq_length_max=100, verbose=False)[source]#
Automatic identification of activity onset/offset times, based on the Crespo algorithm.
Identification of the activity onset and offset times using the algorithm for automatic identification of activity-rest periods based on actigraphy, developed by Crespo et al.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
frequency (int) – Sampling frequency of the actigraphy trace.
zeta (int) – Maximum number of consecutive zeroes considered valid. Default is 15.
zeta_r (int) – Maximum number of consecutive zeroes considered valid (rest). Default is 30.
zeta_a (int) – Maximum number of consecutive zeroes considered valid (active). Default is 2.
t (float) – Percentile for invalid zeroes. Default is 0.33.
alpha (offset) – Average hours of sleep per night. Default is ‘8h’.
beta (offset) – Length of the padding sequence used during the processing. Default is ‘1h’.
estimate_zeta (Boolean) – If set to True, zeta values are estimated from the distribution of ratios of the number of series of consecutive zeroes to the number of series randomly chosen from the actigraphy data. Default is False.
seq_length_max (int) – Maximal length of the aforementioned random series. Default is 100.
verbose – If set to True, print the estimated values of zeta. Default is False.
- Returns:
aot – Arrays containing the estimated activity onset and offset times, respectively.
- Return type:
(ndarray, ndarray)
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Crespo, C., Aboy, M., Fernández, J. R., & Mojón, A. (2012). Automatic identification of activity–rest periods based on actigraphy. Medical & Biological Engineering & Computing, 50(4), 329–340. http://doi.org/10.1007/s11517-012-0875-y [2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514 [3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Oakley(data, threshold=40)[source]#
Oakley’s algorithm for sleep/wake scoring.
Algorithm for automatic sleep/wake scoring based on wrist activity, developed by Oakley.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
threshold (float or str, optional) – Threshold value for scoring sleep/wake. Can be set to “automatic” (cf. Notes). Default is 40.
- Returns:
oakley – Time series containing scores (1: sleep, 0: wake) for each epoch.
- Return type:
pandas.core.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Oakley, N.R. Validation with Polysomnography of the Sleepwatch Sleep/Wake Scoring Algorithm Used by the Actiwatch Activity Monitoring System; Technical Report; Mini-Mitter: Bend, OR, USA, 1997
[2] Instruction manual, Actiwatch Communication and Sleep Analysis Software (https://fccid.io/JIAAWR1/Users-Manual/USERS-MANUAL-1-920937)
[3] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Roenneberg(data, trend_period='24h', min_trend_period='12h', threshold=0.15, min_seed_period='30Min', max_test_period='12h', r_consec_below='30Min', plot=False)[source]#
Automatic sleep detection.
Identification of consolidated sleep episodes using the algorithm developed by Roenneberg et al. [1].
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
trend_period (str, optional) – Time period of the rolling window used to extract the data trend. Default is ‘24h’.
min_trend_period (str, optional) – Minimum time period required for the rolling window to produce a value. Values default to NaN otherwise. Default is ‘12h’.
threshold (float, optional) – Fraction of the trend to use as a threshold for sleep/wake categorization. Default is ‘0.15’
min_seed_period (str, optional) – Minimum time period required to identify a potential sleep onset. Default is ‘30Min’.
max_test_period (str, optional) – Maximal period of the test series. Default is ‘12h’
r_consec_below (str, optional) – Time range to consider, past the potential correlation peak when searching for the maximum correlation peak. Default is ‘30Min’.
plot (bool, optional) – If True, plot the resulting time series. Default is False.
- Returns:
rbg – Time series containing the estimated periods of rest (1) and activity (0).
- Return type:
pandas.core.Series
Notes
Warning
The performance of this algorithm has been evaluated for actigraphy data aggregated in 10-min bins [2]_.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Roenneberg, T., Keller, L. K., Fischer, D., Matera, J. L., Vetter, C., & Winnebeck, E. C. (2015). Human Activity and Rest In Situ. In Methods in Enzymology (Vol. 552, pp. 257-283). http://doi.org/10.1016/bs.mie.2014.11.028
[2] Loock, A., Khan Sullivan, A., Reis, C., Paiva, T., Ghotbi, N., Pilz, L. K., Biller, A. M., Molenda, C., Vuori‐Brodowski, M. T., Roenneberg, T., & Winnebeck, E. C. (2021). Validation of the Munich Actimetry Sleep Detection Algorithm for estimating sleep–wake patterns from activity recordings. Journal of Sleep Research, April, 1–12. https://doi.org/10.1111/jsr.13371
[3] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Roenneberg_AoT(data, trend_period='24h', min_trend_period='12h', threshold=0.15, min_seed_period='30Min', max_test_period='12h', r_consec_below='30Min')[source]#
Automatic identification of activity onset/offset times, based on Roenneberg’s algorithm.
Identification of the activity onset and offset times using the algorithm for automatic identification of consolidated sleep episodes developped by Roenneberg et al. [1]_.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
trend_period (str, optional) – Time period of the rolling window used to extract the data trend. Default is ‘24h’.
min_trend_period (str, optional) – Minimum time period required for the rolling window to produce a value. Values default to NaN otherwise. Default is ‘12h’.
threshold (float, optional) – Fraction of the trend to use as a threshold for sleep/wake categorization. Default is ‘0.15’
min_seed_period (str, optional) – Minimum time period required to identify a potential sleep onset. Default is ‘30Min’.
max_test_period (str, optional) – Maximal period of the test series. Default is ‘12h’
r_consec_below (str, optional) – Time range to consider, past the potential correlation peak when searching for the maximum correlation peak. Default is ‘30Min’.
- Returns:
aot – Arrays containing the estimated activity onset and offset times, respectively.
- Return type:
(ndarray, ndarray)
Notes
Warning
The performance of this algorithm has been evaluated for actigraphy data aggregated in 10-min bins [2]_.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Roenneberg, T., Keller, L. K., Fischer, D., Matera, J. L., Vetter, C., & Winnebeck, E. C. (2015). Human Activity and Rest In Situ. In Methods in Enzymology (Vol. 552, pp. 257-283). http://doi.org/10.1016/bs.mie.2014.11.028
[2] Loock, A., Khan Sullivan, A., Reis, C., Paiva, T., Ghotbi, N., Pilz, L. K., Biller, A. M., Molenda, C., Vuori‐Brodowski, M. T., Roenneberg, T., & Winnebeck, E. C. (2021). Validation of the Munich Actimetry Sleep Detection Algorithm for estimating sleep–wake patterns from activity recordings. Journal of Sleep Research, April, 1–12. https://doi.org/10.1111/jsr.13371
[3] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Sadeh(data, offset=7.601, weights=None, threshold=0.0)[source]#
Sadeh algorithm for sleep identification
Algorithm for automatic sleep scoring based on wrist activity, developped by Sadeh et al [1]_.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
offset (float, optional) – Offset parameter. Default is 7.601.
weights (np.array) – Array of weighting factors for mean_W5, NAT, sd_Last6 and logAct. Default is [-0.065, -1.08, -0.056, -0.703].
threshold (float, optional) – Threshold value for scoring sleep/wake. Default is 0.0.
- Returns:
Sleep–wake classification time series with the same
DatetimeIndexas the input data. Values are binary, where1indicates sleep and0indicates wake, as determined by the Sadeh scoring rule and the specified threshold.- Return type:
pandas.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Sadeh, A., Alster, J., Urbach, D., & Lavie, P. (1989). Actigraphically based automatic bedtime sleep-wake scoring: validity and clinical applications. Journal of ambulatory monitoring, 2(3), 209-216.
[2] Sadeh, A., Sharkey, M., & Carskadon, M. A. (1994). Activity-Based Sleep-Wake Identification: An Empirical Test of Methodological Issues. Sleep, 17(3), 201–207. http://doi.org/10.1093/sleep/17.3.201
[3] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.Scripps(data, scale=0.204, window=None, threshold=1.0)[source]#
Scripps Clinic algorithm for sleep-wake identification.
Algorithm for automatic sleep scoring based on wrist activity, developed by Kripke et al.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
scale (float, optional) – Scale parameter P Default is 0.204.
window (np.array, optional) – Array of weighting factors \(W_{i}\) Default values are identical to those found in the original publication [1]_.
threshold (float, optional) – Threshold value for scoring sleep/wake. Default is 1.0.
- Returns:
scripps – Time series containing the D scores (1: sleep, 0: wake) for each epoch.
- Return type:
pandas.core.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Kripke, D. F., Hahn, E. K., Grizas, A. P., Wadiak, K. H., Loving, R. T., Poceta, J. S., … Kline, L. E. (2010). Wrist actigraphic scoring for sleep laboratory patients: algorithm development. Journal of Sleep Research, 19(4), 612–619. http://doi.org/10.1111/j.1365-2869.2010.00835.x
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[3] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.SleepMidPoint(data, bin_threshold=None, to_td=True, algo='Roenneberg', *args, **kwargs)[source]#
Sleep midpoint
Center of the mean sleep periods.
The sleep midpoint is defined as the time halfway between sleep onset and wake-up time.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
bin_threshold (bool, optional) – If bin_threshold is not set to None, scoring data above this threshold are set to 1 and to 0 otherwise. Default is None.
to_td (bool, optional) – If set to true, the sleep midpoint is returned as a Timedelta. Otherwise, it represents the number of minutes since midnight.
algo (str, optional) – Sleep scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguments passed to the scoring algorithm.
- Returns:
smp
- Return type:
float or Timedelta
Notes
Sleep midpoint (SMP) is an index of sleep timing and is calculated as the following [1]:
\[SMP = \frac{1440}{2\pi} arctan2\left( \sum_{j=1}^M\sum_{i=1}^N s_{i,j} \times sin\left(\frac{2\pi t_i}{1440}\right), \sum_{j=1}^M\sum_{i=1}^N s_{i,j} \times cos\left(\frac{2\pi t_i}{1440}\right) \right)\]- with:
\(t_j\), time of day in minutes at epoch j,
\(\delta(s_{i,j}, s_{i+1,j}) = 1\) if \(s_{i,j} = s_{i+1,j}\) and 0 otherwise.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Lunsford-Avery, J. R., Engelhard, M. M., Navar, A. M., & Kollins, S. H. (2018). Validation of the Sleep Regularity Index in Older Adults and Associations with Cardiometabolic Risk. Scientific Reports, 8(1), 14158. https://doi.org/10.1038/s41598-018-32402-5
[2] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.SleepProfile(data, freq='15min', algo='Roenneberg', *args, **kwargs)[source]#
Normalized sleep daily profile
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
freq (str, optional) – Resampling frequency. Default is ‘15min’
algo (str, optional) – Sleep scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguements passed to the scoring algorithm.
- Returns:
sleep_prof
- Return type:
YYY
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.SleepRegularityIndex(data, bin_threshold=None, algo='Roenneberg', *args, **kwargs)[source]#
Sleep regularity index
Likelihood that any two time-points (epoch-by-epoch) 24 hours apart are in the same sleep/wake state, across all days.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
freq (str, optional) – Resampling frequency. Default is ‘15min’
bin_threshold (bool, optional) – If bin_threshold is not set to None, scoring data above this threshold are set to 1 and to 0 otherwise. Default is None.
algo (str, optional) – Sleep scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguments passed to the scoring algorithm.
- Returns:
sri
- Return type:
float
Notes
The sleep regularity index (SRI) is defined as:
\[SRI = -100 +\]- rac{200}{M(N-1)} sum_{j=1}^Msum_{i=1}^N
delta(s_{i,j}, s_{i+1,j})
- with:
\(\delta(s_{i,j}, s_{i+1,j}) = 1\) if \(s_{i,j} = s_{i+1,j}\) and 0 otherwise.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Phillips, A. J. K., Clerx, W. M., O’Brien, C. S., Sano, A., Barger, L. K., Picard, R. W., … Czeisler, C. A. (2017). Irregular sleep/wake patterns are associated with poorer academic performance and delayed circadian and sleep/wake timing. Scientific Reports, 7(1), 1–13. https://doi.org/10.1038/s41598-017-03171-4
[2] Lunsford-Avery, J. R., Engelhard, M. M., Navar, A. M., & Kollins, S. H. (2018). Validation of the Sleep Regularity Index in Older Adults and Associations with Cardiometabolic Risk. Scientific Reports, 8(1), 14158. https://doi.org/10.1038/s41598-018-32402-5
[3] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[4] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.SoD(data, whs=4, start='12:00:00', period='5h', algo='Roenneberg', *args, **kwargs)[source]#
Sleep over Daytime
Quantify the volume of epochs identified as sleep over daytime (SoD), using sleep-wake scoring algorithms.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
whs (int, optional) – Window half size. Only valid if start=’AonT’ or ‘AoffT’. Default is 4
start (str, optional) – Start time of the period of interest. Default: ‘12:00:00’ Supported times: ‘AonT’, ‘AoffT’, any ‘HH:MM:SS’
period (str, optional) – Period length. Default is ‘5h’
algo (str, optional) – Sleep scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguements passed to the scoring algorithm.
- Returns:
sod – Time series containing the epochs of rest (1) and activity (0) over the specified period.
- Return type:
pandas.core.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.active_bouts(data, duration_min=None, duration_max=None, algo='Roenneberg', *args, **kwargs)[source]#
Active bouts.
Activity periods identified as active.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
duration_min (str,optional) – Minimal time duration for an active period. Default is None (no filtering).
duration_max (str,optional) – Maximal time duration for an active period. Default is None (no filtering).
algo (str, optional) – Sleep/wake scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguements passed to the scoring algorithm.
- Returns:
active_bouts
- Return type:
a list of pandas.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.active_durations(data, duration_min=None, duration_max=None, algo='Roenneberg', *args, **kwargs)[source]#
Duration of the active bouts.
Duration of the activity periods identified as active.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
duration_min (str,optional) – Minimal time duration for an active period. Default is None (no filtering).
duration_max (str,optional) – Maximal time duration for an active period. Default is None (no filtering).
algo (str, optional) – Sleep/wake scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguements passed to the scoring algorithm.
- Returns:
active_durations
- Return type:
a list of pandas.TimeDelta
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.fSoD(data, whs=12, start='12:00:00', period='5h', algo='Roenneberg', *args, **kwargs)[source]#
Fraction of Sleep over Daytime
Fractional volume of epochs identified as sleep over daytime (SoD), using sleep-wake scoring algorithms.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
whs (int, optional) – Window half size. Default is 4
start (str, optional) – Start time of the period of interest. Supported times: ‘AonT’, ‘AoffT’, any ‘HH:MM:SS’. Default: ‘12:00:00’.
period (str, optional) – Period length. Default is ‘10h’.
algo (str, optional) – Sleep scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguements passed to the scoring algorithm.
- Returns:
fsod – Fraction of epochs scored as sleep, relatively to the length of the specified period.
- Return type:
float
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.main_sleep_bouts(data, report='major')[source]#
Calculate main sleep episodes using the Roenneberg algorithm.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
report (str, optional) – Either ‘major’ or ‘minor’. Default is ‘major’. If set to ‘major’, the function will return a dataframe containing all the major sleep bouts in the recording, along with the mean. If set to ‘minor’, the function will return a dataframe containing all the minor sleep bouts in the recording, along with the mean.
- Returns:
Dataframe containing the main sleep episodes (date, start_time, stop_time and duration).
- Return type:
pd.DataFrame
- circstudio.analysis.sleep.sleep.sleep_bouts(data, duration_min=None, duration_max=None, algo='Roenneberg', *args, **kwargs)[source]#
Sleep bouts.
Activity periods identified as sleep.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
duration_min (str,optional) – Minimal time duration for a sleep period. Default is None (no filtering).
duration_max (str,optional) – Maximal time duration for a sleep period. Default is None (no filtering).
algo (str, optional) – Sleep/wake scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguments passed to the scoring algorithm.
- Returns:
sleep_bouts
- Return type:
a list of pandas.Series
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.sleep_durations(data, duration_min=None, duration_max=None, algo='Roenneberg', *args, **kwargs)[source]#
Duration of the sleep bouts.
Duration of the activity periods identified as sleep.
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
duration_min (str,optional) – Minimal time duration for a sleep period. Default is None (no filtering).
duration_max (str,optional) – Maximal time duration for a sleep period. Default is None (no filtering).
algo (str, optional) – Sleep/wake scoring algorithm to use. Default is ‘Roenneberg’.
*args – Variable length argument list passed to the scoring algorithm.
**kwargs – Arbitrary keyword arguements passed to the scoring algorithm.
- Returns:
sleep_durations
- Return type:
a list of pandas.TimeDelta
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- circstudio.analysis.sleep.sleep.waso(data, frequency, algo='Cole-Kripke', **kwargs)[source]#
Calculate Wake After Sleep Onset (WASO)
- Parameters:
data (pandas.Series, optional) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
frequency (pd.Timedelta) – Sampling frequency of the activity trace in data.
algo – Sleep detection algorithm to use to detect sleep fragments during a consolidated sleep period (as determined by the Roenneberg algorithm). It can be either ‘Cole-Kripke’, ‘Sadeh’ or ‘Scripps’.
**kwargs – Pass the ‘settings’ keyword argument to if Cole-Kripke is used. Available settings are: * “mean”: mean activity per minute * “10sec_max_overlap”: maximum 10-second overlapping epoch per minute * “10sec_max_non_overlap”: maximum 10-second non-overlapping epoch per minute * “30sec_max_non_overlap”: maximum 30-second non-overlapping epoch per minute
- Returns:
pd.Series – A series containing WASO values per day
np.float64 – Mean WASO value
- class circstudio.analysis.sleep.diary.SleepDiary(input_fname, start_time, periods, frequency, header_size=2, state_index=None, state_colour=None)[source]#
Bases:
objectClass for reading sleep diaries.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- property diary#
The dataframe containing the data found in the sleep diary.
- property name#
The name of the subject.
- plot(data)[source]#
Plot the sleep diary.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- property raw_data#
The time series related to the states found in the sleep diary.
- property shaded_area#
The template shape which can be overlaid over a plotly plot of the associated actimetry time series.
- sleep_efficiency(data)[source]#
Computes sleep efficiency as the average total sleep time, as classified by the Roenneberg algorithm, divided by the average total sleep time, as identified in the sleep diary.
- Parameters:
data (pd.Series)
- Returns:
Sleep efficiency (decimal)
- Return type:
float
- sleep_onset_latency(data)[source]#
Computes sleep onset latency using the Roenneberg algorithm to predict sleep onset and the sleep diary to determine total bedtime.
- Parameters:
data (pandas.Series) – Input data series with a DatetimeIndex, where the index specifies the time points and the values represent the input variable (e.g., activity, light). Time and value arrays are extracted from this series.
- Returns:
pd.Series – Array containing sleep onset latency indexed by day of the recording.
pd.Timedelta – Mean sleep onset latency.
- property state_colour#
The colours assigned to the states found in the sleep diary.
- property state_index#
The indices assigned to the states found in the sleep diary.
- state_infos(state)[source]#
Returns summary statistics for a given state
- Parameters:
state (str) – State of interest
- Returns:
mean (pd.Timedelta) – Mean duration of the required state.
std (pd.Timedelta) – Standard deviation of the durations of the required state.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- total_bed_time(state='NIGHT')[source]#
Returns the total in-bed time
- Parameters:
state (str, optional) – State of interest. Default is ‘NIGHT’.
- Returns:
mean (pd.Timedelta) – Mean duration of the required state.
std (pd.Timedelta) – Standard deviation of the durations of the required state.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- total_nap_time(state='NAP')[source]#
Returns the total nap time
- Parameters:
state (str, optional) – State of interest. Default is ‘NAP’.
- Returns:
mean (pd.Timedelta) – Mean duration of the required state.
std (pd.Timedelta) – Standard deviation of the durations of the required state.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863
- total_nowear_time(state='NOWEAR')[source]#
Returns the total ‘no-wear’ time
- Parameters:
state (str, optional) – State of interest. Default is ‘NOWEAR’.
- Returns:
mean (pd.Timedelta) – Mean duration of the required state.
std (pd.Timedelta) – Standard deviation of the durations of the required state.
References
This code is derived from the original implementation in pyActigraphy, distributed under the BSD 3-Clause License. Original author: Grégory Hammad (gregory.hammad@uliege.be).
[1] Hammad, G., Reyt, M., Beliy, N., Baillet, M., Deantoni, M., Lesoinne, A., Muto, V., & Schmidt, C. (2021). pyActigraphy: Open-source python package for actigraphy data visualization and analysis. PLoS Computational Biology, 17(10), 1009514–1009535. https://doi.org/10.1371/journal.pcbi.1009514
[2] Hammad, G., Wulff, K., Skene, D. J., Münch, M., & Spitschan, M. (2024). Open-Source Python Module for the Analysis of Personalized Light Exposure Data from Wearable Light Loggers and Dosimeters. LEUKOS, 20(4), 380–389. https://doi.org/10.1080/15502724.2023.2296863