1- """Tab 0b - Batch overview (grouped metrics & plots)."""
2-
3- from __future__ import annotations
4-
5- import sys
6- from pathlib import Path
1+ """
2+ Tab 0b - Batch overview (grouped metrics & plots).
73
4+ This module computes summary circadian metrics for every subject in a loaded
5+ batch, displays the results in a table and boxplot, and allows the user to
6+ select the subject used by the individual-level analysis tabs.
7+ """
8+ # Libraries for data processing and plotting
89import pandas as pd
910import plotly .graph_objects as go
11+
12+ # Shiny imports for UI and server functionality
1013from shiny import module , reactive , render , ui
1114from shinywidgets import output_widget , render_widget
1215
13- sys .path .insert (0 , str (Path (__file__ ).resolve ().parent .parent ))
16+ # Library imports used to locate and import the circStudio package
17+ from pathlib import Path
18+ from import_paths import _add_import_path
19+
20+ # Add the parent directory of this file to the import path to ensure that
21+ # the circStudio package can be imported correctly
22+ app_dir = Path (__file__ ).resolve ().parent .parent
23+ _add_import_path (app_dir )
24+
25+ # Import circStudio modules after adding the import path
1426from circstudio .analysis import IS , IV , l5 , m10 , ra # noqa: E402
27+
28+ # Import a utility function for creating empty figures from the common module
1529from modules ._common import empty_fig # noqa: E402
1630
31+ # Define the actigraphy metrics that will be computed and displayed in the
32+ # batch overview tab
1733_METRICS = ["IS" , "IV" , "L5" , "M10" , "RA" ]
1834
19-
35+ # ---------------------------------------------------------------------
36+ # Actigraphy metric calculation
37+ # ---------------------------------------------------------------------
2038def _compute_metrics (series ) -> dict :
21- """Compute the five circadian metrics for one activity series."""
22- out = {}
39+ """Compute five actigraphy metrics for one subject's activity series.
40+
41+ Parameters
42+ ----------
43+ series
44+ Time-indexed activity measurements for a single subject.
45+
46+ Returns
47+ -------
48+ dict
49+ IS, IV, L5, M10, and RA values. Metrics that cannot be calculated
50+ are represented by ``NaN`` so that the remaining results can still
51+ be displayed.
52+ """
53+ # Store all calculated metrics for the current subject
54+ metrics = {}
55+
56+ # calculate IS and IV metrics, handling any exceptions that may arise
2357 for name , fn in (("IS" , IS ), ("IV" , IV )):
2458 try :
25- out [name ] = float (fn (series ))
59+ # Convert the result to a float and store it in the metrics dictionary
60+ metrics [name ] = float (fn (series ))
61+
62+ # Represent failed calculations as missing without stopping the batch
2663 except Exception :
27- out [name ] = float ("nan" )
64+ metrics [name ] = float ("nan" )
65+
66+ # Calculate L5 and M10 metrics, handling any exceptions that may arise
2867 for name , fn in (("L5" , l5 ), ("M10" , m10 )):
2968 try :
69+ # Run the selected metric on the activity series
3070 res = fn (series )
31- out [name ] = float (res [1 ] if isinstance (res , tuple ) else res )
71+
72+ # Convert the result to a float and store it in the metrics dictionary
73+ metrics [name ] = float (res [1 ] if isinstance (res , tuple ) else res )
74+
75+ # Represent failed calculations as missing without stopping the batch
3276 except Exception :
33- out [name ] = float ("nan" )
77+ metrics [name ] = float ("nan" )
78+
79+ # Calculate RA metric, handling any exceptions that may arise
3480 try :
35- out ["RA" ] = float (ra (series ))
81+ # Run the selected metric on the activity series
82+ metrics ["RA" ] = float (ra (series ))
83+
84+ # Represent failed calculations as missing without stopping the batch
3685 except Exception :
37- out ["RA" ] = float ("nan" )
38- return out
39-
86+ metrics ["RA" ] = float ("nan" )
87+
88+ # Return the dictionary containing all computed metrics for the current subject
89+ return metrics
4090
91+ # ---------------------------------------------------------------------
92+ # Batch overview user interface
93+ # ---------------------------------------------------------------------
94+ # Register this function as the UI component of a reusable Shiny module
4195@module .ui
4296def batch_overview_ui ():
97+ """Create the controls and outputs for the batch overview tab."""
98+ # Arrange the controls in a sidebar and the results in the main panel
4399 return ui .layout_sidebar (
44100 ui .sidebar (
101+ # Let the user start metric calculations for the batch
45102 ui .input_action_button (
46103 "run_metrics" ,
47104 "Run metrics on all subjects" ,
48105 class_ = "btn-primary btn-sm" ,
49106 ),
50107 ui .hr (),
108+
109+ # Select which actigraphy metric is displayed in the boxplot
51110 ui .input_select (
52- "box_metric" , "Boxplot metric" , choices = _METRICS , selected = "IS"
111+ "box_metric" ,
112+ "Boxplot metric" ,
113+ choices = _METRICS ,
114+ selected = "IS"
53115 ),
116+
117+ # Insert the subject selector generated from the loaded batch
54118 ui .output_ui ("subject_picker" ),
55119 width = 320 ,
56120 ),
121+ # Explain the purpose of the tab and of the active subject selector
57122 ui .div (
58123 ui .p (
59124 "This tab summarises interdaily stability, intradaily variability, "
@@ -63,96 +128,209 @@ def batch_overview_ui():
63128 ),
64129 class_ = "text-muted small mb-3" ,
65130 ),
131+ # Display the calculated metrics as a dataframe
66132 ui .h4 ("Grouped metrics" ),
67133 ui .output_data_frame ("metrics_table" ),
68134 ui .hr (),
135+ # Display the selected metric grouped by the first batch factor
69136 ui .h4 ("Metric distribution by factor" ),
70137 output_widget ("metrics_box" ),
71138 )
72139
73-
140+ # ---------------------------------------------------------------------
141+ # Batch overview server logic
142+ # ---------------------------------------------------------------------
143+ # Register this function as the server logic for the Shiny module
74144@module .server
75145def batch_overview_server (input , output , session , rv_batch , rv_active_subject ):
76- _results = reactive .Value (None ) # cached metrics DataFrame
146+ """Server logic for the batch overview tab"""
147+ # Cache the metrics DataFrame so it can be shared by the table and plot
148+ _results = reactive .Value (None )
77149
150+ # Recalculate metrics only when the user clicks the run button
78151 @reactive .effect
79152 @reactive .event (input .run_metrics )
80153 def _run ():
154+ """Retrieve the currently loaded batch"""
81155 batch = rv_batch ()
156+
157+ # Stop if there are no subject recordings to analyze
82158 if batch is None or len (batch ) == 0 :
83159 ui .notification_show ("No batch loaded." , type = "warning" )
84- return
160+ return None
161+
162+ # Collect one results row for each subject
85163 rows = []
86- for e in batch .entries :
87- row = {"subject_id" : e .subject_id }
88- for i , fname in enumerate (batch .factor_names ):
89- row [fname ] = (
90- e .factor_levels [i ] if i < len (e .factor_levels ) else ""
91- )
92- row .update (_compute_metrics (e .raw .activity ))
164+
165+ # Process each subject independently so its metadata remains aligned
166+ for entry in batch .entries :
167+ # Start the row with the subject identifier
168+ row = {"subject_id" : entry .subject_id }
169+
170+ # Add the subject's level for every factor defined in the batch
171+ for factor_index , factor_name in enumerate (batch .factor_names ):
172+ # Use the corresponding level when it is available
173+ if factor_index < len (entry .factor_levels ):
174+ factor_level = entry .factor_levels [factor_index ]
175+
176+ # Use an empty label when the subject lacks this factor level
177+ else :
178+ factor_level = ""
179+
180+ # Store the factor level under its factor name
181+ row [factor_name ] = factor_level
182+
183+ # Calculate and add the five metrics for this activity recording
184+ row .update (_compute_metrics (entry .raw .activity ))
93185 rows .append (row )
94- _results .set (pd .DataFrame (rows ))
186+
187+ # Convert the subject-level records into a DataFrame
188+ results_df = pd .DataFrame (rows )
189+
190+ # Store the results DataFrame in the reactive value so it can be accessed
191+ # by the table and plot
192+ _results .set (results_df )
193+
194+ # Inform the user how many subjects were successfully processed
95195 ui .notification_show (
96- f"Computed metrics for { len (rows )} subject(s)." , type = "message"
196+ f"Computed metrics for { len (rows )} subject(s)." ,
197+ type = "message"
97198 )
98199
200+ # Render the cached subject-level metrics as a DataFrame in the UI
99201 @render .data_frame
100202 def metrics_table ():
203+ """Display the calculated metrics for all subjects"""
101204 df = _results .get ()
205+
206+ # Show an instruction until the user requests the calculations
102207 if df is None :
103208 return pd .DataFrame (
104209 {"info" : ["Click 'Run metrics on all subjects'." ]}
105210 )
211+
212+ # Copy the results so display formatting does not alter the cache
106213 show = df .copy ()
107- for c in _METRICS :
108- if c in show :
109- show [c ] = show [c ].round (4 )
214+
215+ # Round metric values to four decimal places for readability
216+ for metric in _METRICS :
217+ if metric in show :
218+ show [metric ] = show [metric ].round (4 )
219+
220+ # Return an interactive grid that fills the available width
110221 return render .DataGrid (show , width = "100%" )
111222
223+ # Render the selected metric as a Plotly boxplot
112224 @render_widget
113225 def metrics_box ():
226+ """Plot the distribution of one metric across subjects and groups"""
114227 df = _results .get ()
228+
229+ # Display a placeholder until the metrics have been computed
115230 if df is None :
116- return empty_fig ("Run metrics to see the distribution." )
231+ return empty_fig (
232+ "Run metrics to see the distribution."
233+ )
234+
235+ # Read the metric selected in the sidebar
117236 metric = input .box_metric ()
237+
238+ # Guard against a metric being absent from the results
118239 if metric not in df :
119240 return empty_fig ("Metric not available." )
120241
242+ # Retrieve the batch metadata used to identify factors
121243 batch = rv_batch ()
122- factor = batch .factor_names [0 ] if batch and batch .factor_names else None
244+
245+ # Use the first factor in the batch to group the boxplot, if available
246+ if batch :
247+ factor = batch .factor_names [0 ]
248+ else :
249+ factor = None
250+
251+ # Create an empty Plotly figure
123252 fig = go .Figure ()
253+
254+ # Draw a separate boxplot for each level of the factor
124255 if factor and factor in df :
125- for level , sub in df .groupby (factor ):
256+ for factor_level , group_df in df .groupby (factor ):
126257 fig .add_trace (
127- go .Box (y = sub [metric ], name = str (level ), boxpoints = "all" )
258+ go .Box (
259+ y = group_df [metric ],
260+ name = str (factor_level ),
261+ boxpoints = "all"
262+ )
128263 )
264+
265+ # Label the horizontal axis with the factor name
129266 fig .update_layout (xaxis_title = factor )
267+
268+ # Draw a single boxplot when the batch has no factor for grouping
269+ else :
270+ fig .add_trace (
271+ go .Box (
272+ y = df [metric ],
273+ name = "all" ,
274+ boxpoints = "all"
275+ )
276+ )
277+
278+ if factor :
279+ plot_title = f"{ metric } by { factor } "
130280 else :
131- fig .add_trace (go .Box (y = df [metric ], name = "all" , boxpoints = "all" ))
281+ plot_title = metric
282+
283+ # Include the factor in the title when one is being used
132284 fig .update_layout (
133285 yaxis_title = metric ,
134- title = f"{ metric } by { factor } " if factor else metric ,
135- margin = dict (l = 40 , r = 20 , t = 40 , b = 30 ),
286+ title = plot_title ,
287+ margin = {
288+ "l" : 40 ,
289+ "r" : 20 ,
290+ "t" : 40 ,
291+ "b" : 30
292+ },
136293 )
294+
295+ # Return the completed interactive figure
137296 return fig
138297
139- # -- subject selector that drives the default subject in analysis tabs --
298+
299+ # -----------------------------------------------------------------
300+ # Active subject selection
301+ # -----------------------------------------------------------------
302+ # Render the selector dynamically because its choices depend on the batch
140303 @render .ui
141304 def subject_picker ():
305+ """Create the subject selector from the loaded batch identifiers"""
306+ # Retrieve the currently loaded batch to populate the selector
142307 batch = rv_batch ()
308+
309+ # Show a placeholder when no subject recordings are available
143310 if batch is None or len (batch ) == 0 :
144- return ui .p ("No batch loaded." )
311+ return ui .p (
312+ "No batch loaded."
313+ )
314+
315+ # Populate the selector with all subject identifiers in the batch
145316 return ui .input_select (
146317 "active_subject" ,
147318 "Active subject (used by analysis tabs)" ,
148319 choices = batch .subject_ids (),
149320 )
150321
322+ # Keep the shared active subject value synchronized with the selector
151323 @reactive .effect
152324 def _sync_active_subject ():
325+ """Share the selected subject with the individual analysis tabs"""
153326 try :
327+ # Read the selector value after the dynamic UI has been created
154328 val = input .active_subject ()
329+
330+ # Exit quietly if the selector is not yet available (e.g., no batch loaded)
155331 except Exception :
156- return
332+ return None
333+
334+ # Update the shared value only when a valid subject was selected
157335 if val :
158336 rv_active_subject .set (val )
0 commit comments