Skip to content

strikerdlm/circadian

 
 

Repository files navigation

Circadian

CI Twitter DOI

Welcome to circadian, a computational package for the simulation and analysis of circadian rhythms

Install

circadian can be installed via pip:

pip install circadian

Overview

The circadian package implements key mathematical models in the field such as:

See all the available models at circadian/models.py

Additionally, circadian provides a set of tools for simulating and analzying circadian rhythms:

  • Define light schedules using the Light class and feed directly into the models
  • Calculate phase response curves using the PRCFinder class
  • Generate actograms and phase plots with the circadian.plots module

Finally, the package streamlines the process of reading, processing, and analyzing wereable data via the circadian.readers module.

Check out the documentation for a full overview of the package and its features.

Capabilities

  • Simulation and models: Forger99, Jewett99, Hannay19, Hannay19TP; RK4 integration and utilities for equilibrating initial conditions.
  • Light schedules: LightSchedule helpers for Regular, ShiftWork, SlamShift, SocialJetlag, and custom pulses via from_pulse and composable schedules.
  • Phase analysis: Compute DLMO and CBT markers from model trajectories; tools for Phase Response Curves via PRCFinder, intensity, and dosage response protocols.
  • Plotting: Publication-ready actograms via circadian.plots.Actogram with smoothing, thresholds, secondary zeitgeber, and phase markers.
  • Wearable data: CSV/JSON readers (load_csv, load_json), a DataFrame.wearable accessor, and sample data for quick visualization.
  • Metrics: ESRI (Entrainment Signal Regularity Index) computation utilities.
  • Command line: Scriptable actograms and ESRI workflows in circadian/cli.py.
  • Interactive UI: Streamlit app (Circadian Explorer) with interactive ECharts visualizations for model simulation and wearable data (Amplitude & Phase, Actogram heatmaps with DLMO/CBT overlays, ESRI). See the Streamlit section below.

Streamlit app (Circadian Explorer)

Run an interactive UI to simulate models, explore light schedules, and visualize results with ECharts.

  1. Install Python dependencies
pip install -r requirements.txt
  1. Install ECharts (recommended for local assets)
npm install
  • This installs echarts into node_modules/ per package.json. The app will automatically fall back to a CDN if ECharts is not installed locally, but local install is recommended for offline use and faster loads.
  1. Launch the app
streamlit run streamlit_app.py
  1. Open the browser URL that Streamlit prints (usually http://localhost:8501).

Interactive capabilities

  • Amplitude and Phase over time for selected models
  • Light overlay (log10(1+lux)) on a secondary axis
  • Actogram Heatmap of light schedule with optional DLMO/CBT overlays
  • ESRI metric over time

UI reference (technical)

The UI exposes model inputs, light schedules, and visualization controls. Below are precise definitions oriented to physiological interpretation of human circadian timing (SCN-driven oscillation) and light transduction.

Simulation tab – Light schedule (zeitgeber)

  • Schedule: Selects a deterministic zeitgeber LightSchedule applied at the cornea (photopic lux). Models convert lux to a retinal drive via a saturating nonlinearity.
    • Regular: Constant daily photoperiod. Parameters:
      • Lux: Corneal photopic illuminance (lx) during wake/light; proxy for melanopic retinal irradiance driving SCN via ipRGC. Higher lux increases α(L) and thus SCN light drive.
      • Lights on/off (h): Local clock times (0–24) defining the light interval each day.
    • ShiftWork: Repeating block of night shifts then days off. Parameters:
      • Lux: Illuminance while awake/working.
      • Night days on / Days off: Work/off block lengths (days); induces non-24 phase demands.
    • SlamShift: Single abrupt shift (± hours) of the photoperiod after a baseline.
      • Lux: As above.
      • Shift (h): Phase delay (+) or advance (−) of the light window.
    • SocialJetlag: Week with regular days followed by delayed weekend schedule.
      • Lux: As above.
      • Regular days: Count of baseline days (typically 5).
      • Weekend bedtime/wake delay (h): Additional delay applied to lights_on/off on weekend.
    • Custom Pulse: Rectangular pulse repeated with period.
      • Pulse Lux: Pulse height (lx).
      • Pulse start/duration (h): Start time and length within each period.
      • Repeat every (h): Pulse periodicity (e.g., 24 for daily, 168 for weekly).
      • Baseline Lux: Constant baseline between pulses.
  • Total days: Simulation horizon in days.
  • Time step (hours): Numerical integration dt (h) for RK4; smaller dt resolves fast transients in n (phototransduction adaptation).

Simulation tab – Advanced

  • Equilibration repetitions: Number of pre-simulation repetitions of the selected schedule used to converge to a limit cycle. This suppresses dependence on arbitrary initial conditions and yields steady-state phase.
  • Overlay DLMO: Marks Dim Light Melatonin Onset as CBTmin − cbt_to_dlmo (default 7 h) in each model; DLMO is used as a proxy for circadian phase of the SCN–pineal axis.
  • Overlay CBTmin: Marks core body temperature minima (model-defined troughs), a canonical phase reference for the SCN pacemaker output.
  • Actogram threshold (Lux): Lux cutoff to dichotomize the actogram into “light” versus “dark” rectangles.
  • Smooth sigma: Gaussian kernel σ (h) used to smooth light streams for robust on/off segmentation.

Simulation tab – Models and examples

  • Models: Choose one or more oscillators:
    • Forger99, Jewett99: 3‑state limit cycle pacemakers with state (x, xc, n); n is the photic drive/phototransduction variable. Phase is arg(x, −xc); amplitude is √(x² + (−xc)²).
    • Hannay19: Macroscopic amplitude–phase oscillator (R, Ψ, n); R is the order-parameter amplitude, Ψ the phase.
    • Hannay19TP: Two‑population variant (Rv, Rd, Ψv, Ψd, n) representing SCN ventral/dorsal couplings; plotted amplitude is Rv.
  • Examples: Prefills canonical light schedules (e.g., 3 night shifts / 2 off; 5+2 social jetlag; single evening pulse).

Wearable data tab

  • File type / Upload: Accepts CSV/JSON following circadian.readers; selects the most informative stream (light_estimate, activity, steps, or wake).
  • Actogram threshold (Lux or proxy): Binarization threshold applied to the uploaded stream.
  • Smooth sigma: Smoothing σ (h) for robust light/activity segmentation.
  • Or load an example: Uses files in circadian/sample_data/.

Interactive charts tab

  • Chart type: Select between Amplitude & Phase, Actogram (heatmap), or ESRI.
  • Smooth lines: Applies curve smoothing in ECharts rendering (visual only).
  • Show light overlay: Adds log10(1+lux) as a semi-transparent series for perceptual scaling of light magnitude.
  • Overlay DLMO/CBTmin: Adds vertical markers using model‑computed phase landmarks.
  • Plot height (px): Canvas height.

Actogram (heatmap):

  • Bin size (hours): Zeitgeber‑time bin height; values are log‑scaled (log10(1+lux)) and averaged per bin; optional markers are rasterized into the heatmap coordinates.

ESRI metric:

  • Analysis days: Window length for ESRI (days) over which the model amplitude is propagated.
  • ESRI dt (h): Sampling stride for ESRI evaluation; smaller values produce denser ESRI time series.
  • Initial amplitude: Seed amplitude; equals the ESRI value in constant darkness (reference of 0.1 by default).

Physiological glossary and model mapping

  • Lux (photopic): Corneal illuminance; models map lux to a retinal transduction term via α(L).
  • Light transduction α(L): Saturating nonlinearity; e.g., α = α0 (L/I0)^p or α = α0 L^p / (L^p + I0); I0 is the semisaturation constant; p shapes nonlinearity.
  • SCN light drive : Effective drive term combining transduction and adaptation (e.g., B̂ = G (1−n) α …), where n recovers with time (minutes–hours) and reduces sensitivity during sustained light.
  • Phase (φ): For Forger99/Jewett99/Skeldon23, φ = arg(x, −xc); for Hannay19/Hannay19TP, φ = Ψ (or Ψv). UI converts phase to hours via φ_h = φ · 12/π in [0, 24).
  • Amplitude (R): Norm of the oscillator in state space; √(x² + (−xc)²) for 3‑state models; R for Hannay models.
  • CBTmin: Model‑derived core body temperature minimum times; used as a robust phase marker. In Hannay models, CBTmin ≈ Ψ = π crossings; in 3‑state models, minima of x.
  • DLMO: Dim Light Melatonin Onset; approximated as CBTmin − cbt_to_dlmo (default 7 h), recognizing stable offset between melatonin secretion onset and CBT minima.
  • Equilibration: Repetition of the zeitgeber until sequential DLMO markers converge (steady entrained limit cycle); prevents transient‑dependent phase estimation.
  • Zeitgeber time (ZT): Clock time aligned to the external cycle; ZT 0 corresponds to time % 24 == 0.
  • ESRI: Entrainment Signal Regularity Index. Implemented by simulating an amplitude–phase oscillator (Hannay19) with K = 0, γ = 0 so amplitude is constant in darkness; under a given light schedule, the propagated amplitude after analysis_days quantifies temporal regularity of the zeitgeber. Negative values are treated as invalid (NaN).

Example

The code below shows how to simulate the circadian rhythm of a shift worker for four different models and visualize the results in an actogram plot

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
from circadian.plots import Actogram
from circadian.lights import LightSchedule
from circadian.models import Forger99, Jewett99, Hannay19, Hannay19TP

days_night = 3
days_day = 2
slam_shift = LightSchedule.ShiftWork(lux=300.0, days_on=days_night, days_off=days_day)

total_days = 30
time = np.arange(0, 24*total_days, 0.10)
light_values = slam_shift(time)

f_model = Forger99()
kj_model = Jewett99()
spm_model = Hannay19()
tpm_model = Hannay19TP()

equilibration_reps = 2
initial_conditions_forger = f_model.equilibrate(time, light_values, equilibration_reps)
initial_conditions_kj = kj_model.equilibrate(time, light_values, equilibration_reps)
initial_conditions_spm = spm_model.equilibrate(time, light_values, equilibration_reps)
initial_conditions_tpm = tpm_model.equilibrate(time, light_values, equilibration_reps)

The models are integrated using an explicit Runge-Kutta 4 (RK4) scheme

trajectory_f = f_model(time, initial_conditions_forger, light_values)
trajectory_kj = kj_model(time, initial_conditions_kj, light_values)
trajectory_spm = spm_model(time, initial_conditions_spm, light_values)
trajectory_tpm = tpm_model(time, initial_conditions_tpm, light_values)

The Dim Light Melatonin Onset (DLMO), an experimental measurement of circadian phase, is calculated for each model by

dlmo_f = f_model.dlmos()
dlmo_kj = kj_model.dlmos()
dlmo_spm = spm_model.dlmos()
dlmo_tpm = tpm_model.dlmos()

Lastly, the results of the simulation–DLMOs included– are visualized in an Actogram plot from the circadian.plots module

acto = Actogram(time, light_vals=light_values, opacity=1.0, smooth=False)
acto.plot_phasemarker(dlmo_f, color='blue')
acto.plot_phasemarker(dlmo_spm, color='darkgreen')
acto.plot_phasemarker(dlmo_tpm, color='red')
acto.plot_phasemarker(dlmo_kj, color='purple')
# legend
blue_line = lines.Line2D([], [], color='blue', label='Forger99')
green_line = lines.Line2D([], [], color='darkgreen', label='Hannay19')
red_line = lines.Line2D([], [], color='red', label='Hannay19TP')
purple_line = lines.Line2D([], [], color='purple', label='Jewett99')

plt.legend(handles=[blue_line, purple_line, green_line, red_line], 
           loc='upper center', bbox_to_anchor=(0.5, 1.12), ncol=4)
plt.title("Actogram for a Simulated Shift Worker", pad=35)
plt.tight_layout()
plt.show()

Contributing

We welcome contributions to circadian via issues, pull requests, or comments! Please see our contributing guidelines for more information.

Acknowledgements

UI updates for the Streamlit app and related UX improvements were contributed by Dr. Diego L. Malpica.

About the contributor

  • Diego L. Malpica — Aerospace Medicine researcher focused on human performance in extreme environments, integrating AI and advanced analytics for operational decision-making.
  • ORCID: 0000-0002-2257-4940
  • LinkedIn: in/diegolmalpica

Citation

If you find circadian useful, please cite as:

@software{franco_tavella_2023_8206871,
  author       = {Franco Tavella and
                  Kevin Hannay and
                  Olivia Walch},
  title        = {{Arcascope/circadian: Refactoring of readers and 
                   metrics modules}},
  month        = aug,
  year         = 2023,
  publisher    = {Zenodo},
  version      = {v1.0.2},
  doi          = {10.5281/zenodo.8206871},
  url          = {https://doi.org/10.5281/zenodo.8206871}
}

Head to https://doi.org/10.5281/zenodo.8206871 for more information on the latest release.

About

Tools for the simulation and analysis of circadian rhythms

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Jupyter Notebook 93.7%
  • Python 5.8%
  • Other 0.5%