Skip to content

Commit 82d967d

Browse files
authored
Merge pull request #2 from djmarques/main
GUI for circStudio
2 parents 2d7938b + f30cfa0 commit 82d967d

37 files changed

Lines changed: 609328 additions & 0 deletions

‎.DS_Store‎

10 KB
Binary file not shown.

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
*.pyc
2+
.DS_Store

‎app/.DS_Store‎

10 KB
Binary file not shown.

‎app/app.py‎

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
"""
2+
circStudio Shiny web app
3+
-------------------------
4+
Each analysis tab is a Shiny module in its own file in the modules package. This file
5+
assembles them into a single Shiny app and defines the per-session reactive state passed
6+
to every module.
7+
8+
Each analysis page has two parts:
9+
1. A ``*_ui``function, which defines what the user sees in the browser.
10+
2. A ``*_server``function, which defines what happens when the user uploads data, clicks
11+
buttons, changes parameters, or requests plots.
12+
13+
Launch with::
14+
15+
cd /path/to/circStudio
16+
pip install -e src/
17+
pip install -r app/requirements.txt
18+
shiny run app/app.py
19+
20+
The three top-level reactive values (``rv_single``, ``rv_batch``, ``rv_mode``)
21+
plus a shared ``rv_active_subject`` are created per session and threaded into
22+
each module so the analysis tabs always operate on the active recording.
23+
24+
Data flow
25+
----------
26+
The app keeps four shared reactive (rv) values per user session:
27+
28+
``rv_single``
29+
Holds one uploaded actigraphy file, i.e., a ``Raw``object.
30+
31+
``rv_batch``
32+
Holds a batch collection when several a directory with several recordings
33+
is specified.
34+
35+
``rv_mode``
36+
Either "single" or "batch", depending on whether the user uploaded a single
37+
recording or specified a directory with several recordings.
38+
39+
``rv_active_subject```
40+
In batch mode, stores which subject is currently selected for analysis.
41+
42+
These values are passed into the modlules so that all tabsanalyse the same currently
43+
active recording or subject.
44+
"""
45+
# ---------------------------------------------------------------------------
46+
# Project directory structure
47+
# ---------------------------------------------------------------------------
48+
# circStudio/
49+
# ├── app/
50+
# │ ├── app.py
51+
# │ ├── modules/
52+
# │ └── www/
53+
# └── src/
54+
# └── circstudio/
55+
#
56+
# The code below constructs this structure from the location of app.py
57+
# ---------------------------------------------------------------------------
58+
59+
from pathlib import Path
60+
from import_paths import _add_import_path
61+
62+
# Absolute path to this app.py file (Path(__file__) == path to this file)
63+
_this_file = Path(__file__).resolve()
64+
65+
# Directory containing this app.py file (app/)
66+
app_dir = _this_file.parent
67+
68+
# Project (circStudio/) directory
69+
_project_dir = app_dir.parent
70+
71+
# Source code directory containing the circStudio package
72+
src_dir = _project_dir / "src"
73+
74+
# Put app/ and src/ on the import path so `modules`, `utils`, and `circstudio` resolve
75+
_add_import_path(app_dir)
76+
_add_import_path(src_dir)
77+
78+
# HTMLDependency is used to include a custom CSS theme for the app
79+
from htmltools import HTMLDependency # noqa: E402
80+
81+
# Shiny core imports:
82+
# - App: application object
83+
# - reactive: reactive values/effects/calculations
84+
# - ui: user interface constructors
85+
from shiny import App, reactive, ui # noqa: E402
86+
87+
# Import modules for each analysis tab. Each module has a *_ui and *_server function
88+
from modules.upload import upload_ui, upload_server # noqa: E402
89+
from modules.preprocessing import preprocessing_ui, preprocessing_server # noqa: E402
90+
from modules.batch_overview import batch_overview_ui, batch_overview_server # noqa: E402
91+
from modules.daily_profile import daily_profile_ui, daily_profile_server # noqa: E402
92+
from modules.sleep import sleep_ui, sleep_server # noqa: E402
93+
from modules.cosinor import cosinor_ui, cosinor_server # noqa: E402
94+
from modules.lids import lids_ui, lids_server # noqa: E402
95+
from modules.fractal import fractal_ui, fractal_server # noqa: E402
96+
from modules.flm import flm_ui, flm_server # noqa: E402
97+
from modules.ssa import ssa_ui, ssa_server # noqa: E402
98+
from modules.circ_models import circ_models_ui, circ_models_server # noqa : E402
99+
from modules.llm_chat import llm_chat_ui, llm_chat_server # noqa: E402
100+
101+
# ---------------------------------------------------------------------------
102+
# Styling
103+
# ---------------------------------------------------------------------------
104+
# This links the custom CSS file located in app/www/theme.css.
105+
_THEME_DEP = HTMLDependency(
106+
name="circstudio-theme",
107+
version="1.0.0",
108+
head='<link rel="stylesheet" href="theme.css">',
109+
)
110+
111+
# Build the main app navigation bar, with one tab for each analysis module
112+
app_ui = ui.page_navbar(
113+
ui.nav_panel("Data Upload", upload_ui("upload")),
114+
ui.nav_panel("Preprocessing", preprocessing_ui("preprocess")),
115+
ui.nav_panel("Batch Overview", batch_overview_ui("batch")),
116+
ui.nav_panel("Daily Profile", daily_profile_ui("daily")),
117+
ui.nav_panel("Sleep Scoring", sleep_ui("sleep")),
118+
ui.nav_panel("Cosinor", cosinor_ui("cosinor")),
119+
ui.nav_panel("LIDS", lids_ui("lids")),
120+
ui.nav_panel("Fractal / MFDFA", fractal_ui("fractal")),
121+
ui.nav_panel("FLM", flm_ui("flm")),
122+
ui.nav_panel("SSA", ssa_ui("ssa")),
123+
ui.nav_panel("Circadian Models", circ_models_ui("circ")),
124+
ui.nav_panel("Assistant", llm_chat_ui("chat")),
125+
title="circStudio",
126+
id="main_nav",
127+
header=_THEME_DEP,
128+
)
129+
130+
def server(input, output, session):
131+
# -----------------------------------------------------------------------
132+
# Per-session reactive state
133+
# -----------------------------------------------------------------------
134+
# Reactive values are containers that notify downstream code when their
135+
# contents change. For example, when a user uploads a new recording, tabs
136+
# that depend on that recording can automatically update
137+
138+
# Holds a single ``Raw``object
139+
rv_single = reactive.Value(None)
140+
141+
# Holds a batch collection of recordings
142+
rv_batch = reactive.Value(None)
143+
144+
# Either "single" or "batch"
145+
rv_mode = reactive.Value("single")
146+
147+
# Current subject in batch mode
148+
rv_active_subject = reactive.Value(None)
149+
150+
# -----------------------------------------------------------------------
151+
# Connect each tab's server to the shared reactive state. The following
152+
# four variables constitute the app's shared memory:
153+
#
154+
# rv_single: single loaded actigraphy recording (single mode)
155+
# rv_batch: batch collection of recordings (batch mode)
156+
# rv_mode: "single" or "batch"
157+
# rv_active_subject: current subject in batch mode
158+
#
159+
# When one tab updates one, the others will react automatically.
160+
# -----------------------------------------------------------------------
161+
162+
# The loading module does not neeed information about the selected subject
163+
upload_server(
164+
"upload",
165+
rv_single,
166+
rv_batch,
167+
rv_mode
168+
)
169+
170+
# The preprocessing module needs information on the selected subject
171+
preprocessing_server(
172+
"preprocess",
173+
rv_single,
174+
rv_batch,
175+
rv_mode,
176+
rv_active_subject
177+
)
178+
179+
# The batch module onlyb requires information about the collection
180+
# And selected subject
181+
batch_overview_server(
182+
"batch",
183+
rv_batch,
184+
rv_active_subject
185+
)
186+
187+
# All remaining modules take the same four values, set them up in a loop
188+
for tab_id, server_func in (
189+
("daily", daily_profile_server),
190+
("sleep", sleep_server),
191+
("cosinor", cosinor_server),
192+
("lids", lids_server),
193+
("fractal", fractal_server),
194+
("flm", flm_server),
195+
("ssa", ssa_server),
196+
("circ", circ_models_server),
197+
("chat", llm_chat_server)
198+
):
199+
server_func(tab_id, rv_single, rv_batch, rv_mode, rv_active_subject)
200+
201+
# Assemble the Shiny app from the UI layout and server logic
202+
# Serve static files (CSS) from app/www
203+
app = App(app_ui, server, static_assets=app_dir / "www")

‎app/import_paths.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import sys
2+
from pathlib import Path
3+
4+
def _add_import_path(folder: Path) -> None:
5+
"""
6+
Add a local folder to Python's import search path.
7+
8+
Parameters
9+
----------
10+
path:
11+
Folder that should be search when importing Python modules.
12+
13+
Notes
14+
-----
15+
``sys.path.insert(0, ...)`` puts the folder at the beginning of the
16+
search path, so that local modules are found before any installed packages.
17+
"""
18+
if folder.is_dir():
19+
sys.path.insert(0, str(folder))

‎app/modules/.DS_Store‎

6 KB
Binary file not shown.

‎app/modules/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Shiny module package for the circStudio app."""

‎app/modules/_common.py‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
"""Helpers shared by the analysis tab modules.
2+
3+
These functions implement the per-tab subject/factor selectors used in batch
4+
mode and a couple of small Plotly utilities. They are deliberately kept
5+
free of module-specific state so every analysis tab can reuse them.
6+
"""
7+
8+
from __future__ import annotations
9+
10+
from typing import Optional
11+
12+
import numpy as np
13+
import pandas as pd
14+
import plotly.graph_objects as go
15+
from shiny import ui
16+
17+
import sys
18+
from pathlib import Path
19+
20+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
21+
from utils import active_raw # noqa: E402
22+
23+
24+
def as_series(x) -> Optional[pd.Series]:
25+
"""Coerce activity/light data to a clean 1-D pandas Series.
26+
27+
Some readers (e.g. AGD) return the light channel as a one-column
28+
DataFrame; several metric functions only accept a Series, so this picks a
29+
single column (preferring a ``LIGHT`` column) while preserving the
30+
DatetimeIndex and its frequency.
31+
"""
32+
if x is None:
33+
return None
34+
if isinstance(x, pd.Series):
35+
return x
36+
if isinstance(x, pd.DataFrame):
37+
if x.shape[1] == 0:
38+
return None
39+
col = "LIGHT" if "LIGHT" in x.columns else x.columns[0]
40+
return x[col]
41+
return pd.Series(np.ravel(x))
42+
43+
44+
def activity_series(raw) -> Optional[pd.Series]:
45+
if raw is None:
46+
return None
47+
return as_series(getattr(raw, "activity", None))
48+
49+
50+
def light_series(raw) -> Optional[pd.Series]:
51+
if raw is None:
52+
return None
53+
s = as_series(getattr(raw, "light", None))
54+
if s is None or len(s) == 0:
55+
return None
56+
return s
57+
58+
59+
def empty_fig(message: str = "No data loaded.") -> go.Figure:
60+
"""A blank Plotly figure carrying an informational annotation."""
61+
fig = go.Figure()
62+
fig.update_layout(
63+
xaxis=dict(visible=False),
64+
yaxis=dict(visible=False),
65+
annotations=[
66+
dict(
67+
text=message,
68+
xref="paper",
69+
yref="paper",
70+
showarrow=False,
71+
font=dict(size=16, color="#888"),
72+
)
73+
],
74+
margin=dict(l=20, r=20, t=20, b=20),
75+
)
76+
return fig
77+
78+
79+
def factor_filter_controls(rv_mode, rv_batch):
80+
"""Return the factor-level filter select (batch mode only) or ``None``."""
81+
if rv_mode() != "batch":
82+
return None
83+
batch = rv_batch()
84+
if batch is None or len(batch) == 0:
85+
return None
86+
if not batch.factor_names:
87+
return None
88+
levels = ["(all)"] + batch.levels_for_factor(0)
89+
return ui.input_select(
90+
"factor_filter",
91+
"Filter by first factor",
92+
choices=levels,
93+
selected="(all)",
94+
)
95+
96+
97+
def subject_controls(input, rv_mode, rv_batch, default=None):
98+
"""Return the subject select for the current mode/filter, or ``None``.
99+
100+
``default`` (e.g. the globally selected subject from the Batch Overview
101+
tab) is used as the initially selected value when it is among the choices.
102+
"""
103+
if rv_mode() != "batch":
104+
return None
105+
batch = rv_batch()
106+
if batch is None or len(batch) == 0:
107+
return None
108+
109+
level = None
110+
if batch.factor_names:
111+
try:
112+
sel = input.factor_filter()
113+
if sel and sel != "(all)":
114+
level = sel
115+
except Exception:
116+
level = None
117+
118+
entries = batch.filter(0, level) if level else batch.entries
119+
choices = [e.subject_id for e in entries]
120+
if not choices:
121+
choices = batch.subject_ids()
122+
selected = default if default in choices else None
123+
return ui.input_select(
124+
"subject", "Subject", choices=choices, selected=selected
125+
)
126+
127+
128+
def selected_subject(input) -> Optional[str]:
129+
"""Read the per-tab subject selector value if present."""
130+
try:
131+
val = input.subject()
132+
return val or None
133+
except Exception:
134+
return None
135+
136+
137+
def get_active(input, rv_mode, rv_single, rv_batch):
138+
"""Resolve the Raw object this tab should use (single or batch)."""
139+
return active_raw(rv_mode, rv_single, rv_batch, selected_subject(input))

0 commit comments

Comments
 (0)