An interactive research and educational tool for exploring cognitive theory paradigms in surgical monitoring. This app demonstrates three theory-driven approaches to adaptive threshold control, allowing researchers and students to understand the cognitive mechanisms underlying surgical performance.
Looking for real-time monitoring? See the Surgical Cognitive Dashboard for production-ready live monitoring with ML diagnostics.
This Training Lab is a pure theoretical exploration tool - no live monitoring, no diagnostics, just interactive cognitive theory.
What This Tool Does:
- Explore 3 Cognitive Theories through interactive parameter controls
- Compare Threshold Paradigms side-by-side
- Teach Cognitive Neuroscience concepts in surgery
- Prototype New Algorithms before production implementation
- Understand Theory-to-Practice translation
What This Tool Does NOT Do:
- β Real-time surgical monitoring (use Production Dashboard)
- β ML model diagnostics (use Production Dashboard)
- β Clinical decision support
- β Patient data handling
Theory: Aston-Jones & Cohen's (2005) Adaptive Gain Theory + Yerkes-Dodson Law
Core Concept:
Performance follows an inverted-U curve with arousal:
- Sub-optimal arousal β Need more challenge
- Optimal arousal β Peak performance
- Hyper-arousal β Overwhelmed
How It Works:
- Monitors pupil diameter as arousal proxy
- Defines three arousal zones with boundaries
- Automatically adjusts thresholds based on current zone
- Implements the "sweet spot" of performance
Interactive Parameters:
- π Arousal zone boundaries (sub-optimal β optimal β hyper)
- ποΈ Threshold adjustments per zone
- β‘ Adaptation reactivity speed
Use Case:
Surgical training where you want to keep learners in the optimal challenge zone
Theory: Norman & Bobrow's (1975) Resource Theory + Kahneman's (1973) Capacity Model
Core Concept:
Cognitive resources are finite and shared:
- High sensitivity β Detect everything (more false alarms)
- Low sensitivity β Only critical events (miss subtle signs)
- Classic signal detection theory trade-off
How It Works:
- Single "sensitivity" slider controls both thresholds
- Lower high-load threshold = more sensitive to overload
- Lower lapse threshold = more sensitive to inattention
- Explicit precision-recall trade-off
Interactive Parameters:
- ποΈ System sensitivity (0-100%)
- π Coupling factor (how tightly thresholds move together)
- π Baseline offsets for independent adjustment
Use Case:
Research comparing liberal vs. conservative detection strategies
Theory: Warm et al. (2008) Vigilance Theory + Time-on-Task Effect
Core Concept:
Sustained attention degrades over time:
- First 10 minutes β Optimal vigilance
- After 30 minutes β Vigilance decrement begins
- After 60 minutes β Significant performance drop
How It Works:
- Tracks time-on-task automatically
- Lowers thresholds as fatigue increases
- Compensates for reduced operator sensitivity
- Implements non-linear fatigue curves
Interactive Parameters:
- β° Fatigue onset time (when decrement begins)
- π Maximum threshold adjustment
- π Fatigue curve shape (linear, exponential, step)
- π Recovery rate (for break modeling)
Use Case:
Long surgical procedures where fatigue is a known factor
This application implements three threshold policy controllers with parameter names and semantics that exactly match the accompanying case study documentation. Each policy is a pure R function in R/policies.R with precise mathematical specifications.
Function: adaptive_gain_perf(x, k, scale)
Purpose: Demonstrates the inverted-U relationship between arousal and performance.
Parameters:
k(numeric): Curve sharpness, controls how quickly performance falls off from the peak- Range: 0.1 to 1.0
- Default: 0.4
- Higher k = sharper peak, narrower optimal zone
scale(numeric): Global performance scale factor- Range: 0.5 to 2.0
- Default: 1.0
Theory: Yerkes-Dodson Law / Adaptive Gain Theory
Use Case: Intuition plot showing optimal mid-arousal performance zone
Function: sdt_dual_criterion(criterion_tightness, coupling, hys_margin, base_hl, base_lapse, move_range)
Purpose: Two decision criteria (high-load and lapse) with hysteresis to prevent edge chatter.
Parameters:
criterion_tightness(0β1): How tightly criteria are set- Default: 0.60
- 0 = loose (wide normal zone), 1 = tight (narrow normal zone)
coupling(0β1): How much the lapse criterion follows the high-load criterion- Default: 0.70
- 1 = symmetric movement, 0 = only high-load moves
hys_margin(numeric): Hysteresis margin (enterβexit gap)- Range: 0.00 to 0.50
- Default: 0.15
- Creates "sticky" zones to reduce rapid state transitions
base_hl(numeric): Baseline high-load criterion in evidence units- Default: 1.60
base_lapse(numeric): Baseline lapse criterion in evidence units- Default: -1.60
move_range(numeric): Maximum criterion movement range- Default: 1.00
Returns: List with 6 thresholds: crit_hl, crit_lapse, hi_enter, hi_exit, lo_enter, lo_exit
Theory: Signal Detection Theory with dual criteria and hysteresis
Use Case: Tuning bias (not sensitivity dβ²); prevents edge chatter
Function: time_on_task_threshold(t, c_start, c_floor, onset_min, fatigue_half_life_min, microbreak_min, microbreak_reset_fixed, microbreak_decay_min, phys_opt)
Purpose: Decision threshold that relaxes with fatigue and briefly tightens after microbreak.
Parameters:
t(numeric vector): Time in minutesc_start(0β1): Initial decision threshold- Default: 0.70
- Held constant until onset
c_floor(0β1): Asymptotic floor threshold- Default: 0.50
- Target for exponential decay
onset_min(numeric): Fatigue onset time in minutes- Default: 30
- Threshold relaxes after this point
fatigue_half_life_min(numeric): Time to decay halfway from c_start to c_floor- Default: 21
- Controls decay rate
microbreak_min(numeric): Microbreak time in minutes- Default: 60
- NA or 0 for no break
microbreak_reset_fixed(0β1): Fixed reset magnitude after break- Default: 0.08
- Can be replaced by physiology-proportional reset
microbreak_decay_min(numeric): Time constant for reset decay- Default: 2
- How quickly the reset benefit fades
phys_opt(list, optional): Pre/post physiology for proportional reset- Columns:
RMSSD_pre,RMSSD_post,TEPR_pre,TEPR_post,Tremor_pre,Tremor_post - Formula:
reset = alpha * phi * gapwhere phi is weighted recovery index
- Columns:
Returns: Numeric vector of threshold values over time
Theory: Vigilance Decrement / Time-on-Task Effects
Use Case: Hold steady until onset; relax with half-life; microbreak briefly tightens threshold
Key Behavior: Reset applies ONLY AFTER microbreak (not before)
All parameter names in the UI, functions, and JSON exports match the case study exactly:
β No abbreviations where clarity is needed
β Underscores for multi-word parameters (e.g., criterion_tightness, not criterionTightness)
β Units in names where ambiguous (e.g., onset_min, microbreak_min)
β Semantic clarity over brevity (e.g., hys_margin instead of h or margin)
Each policy can be exported as JSON with this structure:
{
"kind": "dual_criterion",
"params": {
"criterion_tightness": 0.60,
"coupling": 0.70,
"hys_margin": 0.15,
"base_hl": 1.60,
"base_lapse": -1.60,
"move_range": 1.00
},
"thresholds": {
"crit_hl": 1.00,
"crit_lapse": -1.18,
"hi_enter": 1.00,
"hi_exit": 0.85,
"lo_enter": -1.18,
"lo_exit": -1.03
}
}Download via the Export Policy section at the bottom of the app.
Inverted-U performance curve demonstrating the Yerkes-Dodson Law. Adjust k to control curve sharpness.
Dual-criterion setup with hysteresis bands. Blue zone = Normal decision region; gray slivers = hysteresis zones.
Hysteresis reduces edge-chatter: circles (naive) vs triangles (hysteresis) show fewer state transitions.
Fatigue-adaptive threshold with onset, half-life, and microbreak annotations. Reset applies ONLY after break.
Educational content with key references, DOI links, and dashboard mapping.
Note: Screenshots are placeholders. Generate actual screenshots after deployment using browser dev tools or screenshot utilities.
The app supports a complete configuration save/restore cycle:
Export Policy:
- Adjust sliders to desired values
- Select policy type (adaptive_gain, dual_criterion, or time_on_task)
- Click "Export policy JSON"
- Save the downloaded JSON file
Import Policy:
- Click "Import policy JSON"
- Select a previously exported JSON file
- Sliders automatically update to match the imported configuration
- Notification confirms: "β [Policy Type] imported successfully!"
Use Cases:
- πΎ Save configurations for later use
- π Compare different parameter sets
- π€ Share policies with colleagues
- π Maintain a library of validated configurations
- π¬ A/B testing of threshold strategies
The Time-on-Task policy supports optional physiology-proportional reset for microbreaks:
Download Template:
- Click "Download physiology template" in Time-on-Task tab
- Get CSV with 6 columns:
RMSSD_pre,RMSSD_post,TEPR_pre,TEPR_post,Tremor_pre,Tremor_post - Replace example values with real pre/post microbreak measurements
- Upload via file input
How It Works:
- Computes weighted recovery index: Ο = 0.5Γz(ΞRMSSD) + 0.3Γz(βΞTEPR) + 0.2Γz(βΞTremor)
- Scales reset: reset = Ξ± Γ Ο Γ gap (where Ξ±=0.35, gap=c_startβbaseline)
- Larger physiological recovery β Larger threshold reset
- More precise than fixed reset
Example Template Values:
RMSSD_pre,RMSSD_post,TEPR_pre,TEPR_post,Tremor_pre,Tremor_post
40,48,0.30,0.20,85,70Shows positive recovery: RMSSDβ, TEPRβ, Tremorβ
π¬ All evidence data shown in the plots is illustrative demo data, not clinical traces.
- Adaptive Gain: Theoretical curve demonstrating Yerkes-Dodson relationship
- SDT Distributions: Simulated evidence from
rnorm()with fixed means (β2, 0, +2)- SDT Timeseries: AR(1) process with Ο=0.92, not real surgical data
- Time-on-Task: Demonstrates mathematical policy, not actual threshold trace
For real-time surgical monitoring with live data, use the Surgical Cognitive Dashboard.
π This is Signal Detection Theory (SDT) with hysteresis, not a Drift-Diffusion Model (DDM).
- SDT: Dual decision criteria (high-load and lapse) for state classification
- Hysteresis: Enter/exit thresholds add persistence to prevent edge chatter
- Not DDM: We're modeling decision boundaries, not evidence accumulation dynamics
- Why SDT? Real-time stability, interpretability, and computational efficiency
The evidence axis shows a z-scored, signed index (e.g., +wΒ·z(TEPR) β vΒ·z(RMSSD)), not accumulated drift.
# 1. Clone the repository
git clone https://github.com/mohdasti/surgical-training-lab.git
cd surgical-training-lab
# 2. Check dependencies
Rscript check_dependencies.R
# 3. Launch the app
Rscript launch_app.RAlternative: From R Console
# Install dependencies if needed
install.packages(c("shiny", "bslib", "ggplot2", "plotly", "DT",
"shinyjs", "htmltools", "jsonlite"))
# Run the app
shiny::runApp()See DEPENDENCIES.md for detailed dependency information.
- Read the theory cards - Understand the three paradigms
- Explore each paradigm - All three are displayed simultaneously
- Adjust parameters using the interactive controls (sliders, inputs)
- Observe threshold changes in real-time plots
- Compare paradigms side-by-side to understand differences
- Experiment with different values to see how theories behave
- Week 1: Arousal and performance (Inverted-U)
- Week 2: Attention and resource allocation (Unified Sensitivity)
- Week 3: Sustained attention and fatigue (Fatigue-Adaptive)
- Demo: "Why one threshold doesn't fit all situations"
- Activity: Students adjust parameters and predict outcomes
- Discussion: Theory-to-practice translation challenges
- Prototype new paradigms
- Compare against established theories
- Validate on simulated data before clinical testing
| Feature | π§ͺ Training Lab (This Repo) | π₯ Production Dashboard |
|---|---|---|
| Purpose | Theory Exploration | Real-Time Monitoring |
| Tabs | 1 (Theory Explorer Only) | 3 (Live Monitor, Training Lab, Diagnostics) |
| Focus | Educational/Research | Clinical Safety |
| Audience | Researchers, Students, Educators | Clinicians, Hospitals |
| Features | 3 Paradigms + Presets + Comparison | Live HUD + GT Tables + ML Diagnostics |
| Stability | Experimental | Production-Ready |
| Updates | Frequent, Breaking Changes OK | Stable Releases Only |
Decision Guide:
- "I want to understand how cognitive theories affect thresholds" β Use Training Lab β
- "I need to monitor a surgeon in real-time" β Use Production Dashboard
- "I want to teach a grad course on attention" β Use Training Lab β
- "I need ML model diagnostics" β Use Production Dashboard
Adaptive Gain Theory:
- Aston-Jones, G., & Cohen, J. D. (2005). An integrative theory of locus coeruleus-norepinephrine function. Annual Review of Neuroscience, 28, 403-450.
- Yerkes, R. M., & Dodson, J. D. (1908). The relation of strength of stimulus to rapidity of habit-formation. Journal of Comparative Neurology and Psychology, 18(5), 459-482.
Resource Theory:
- Kahneman, D. (1973). Attention and Effort. Prentice-Hall.
- Norman, D. A., & Bobrow, D. G. (1975). On data-limited and resource-limited processes. Cognitive Psychology, 7(1), 44-64.
Vigilance Decrement:
- Warm, J. S., Parasuraman, R., & Matthews, G. (2008). Vigilance requires hard mental work and is stressful. Human Factors, 50(3), 433-441.
- Mackworth, N. H. (1948). The breakdown of vigilance during prolonged visual search. Quarterly Journal of Experimental Psychology, 1(1), 6-21.
surgical-training-lab/
βββ app.R # Main Shiny application (case-study aligned UI)
βββ launch_app.R # Quick launch script
βββ check_dependencies.R # Dependency checker and installer
βββ DESCRIPTION # Package metadata and dependencies
βββ DEPENDENCIES.md # Detailed dependency documentation
βββ QA_CHECKLIST.md # Quality assurance checklist
βββ R/ # Policy functions and modules
β βββ policies.R # Core policy functions (case-study aligned)
β βββ theme.R # Clinical bslib theme with Bootstrap 5
β βββ mod_inverted_u_adjuster.R # Inverted-U module (legacy)
β βββ mod_unified_sensitivity.R # Unified sensitivity module (legacy)
β βββ mod_fatigue_adaptive.R # Fatigue-adaptive module (legacy)
β βββ threshold_utils.R # Threshold utilities
β βββ [...other modules...] # Additional utility modules
βββ config/
β βββ config.yml # Configuration parameters
βββ README.md # This file
Key Files:
R/policies.R: Pure R functions implementing the three threshold policiesR/theme.R: Clinical color palette and Bootstrap 5 themeapp.R: Three-tab UI with exact case-study parameter namesQA_CHECKLIST.md: Comprehensive testing checklist for visual parity
Since you mentioned wanting to embed this in your Quarto case study, here are the options:
# Install rsconnect
install.packages("rsconnect")
# Configure credentials
rsconnect::setAccountInfo(name="your-account",
token="your-token",
secret="your-secret")
# Deploy
rsconnect::deployApp("/path/to/surgical-training-lab")Then embed in your Quarto document:
## Interactive Theory Explorer
<iframe
src="https://your-username.shinyapps.io/surgical-training-lab/"
width="100%"
height="900px"
style="border:1px solid #ddd; border-radius:12px;"
loading="lazy">
</iframe>Convert to run entirely in browser:
# Install shinylive
install.packages("shinylive")
# Export to WebAssembly
shinylive::export("app.R", "docs/")
# Add to Quarto siteFor a non-interactive case study, capture key visuals.
This is a research tool! Contributions welcome:
- New paradigms - Implement your cognitive theory
- Parameter tuning - Improve defaults based on literature
- Educational materials - Lesson plans, activities, examples
- Bug fixes - Especially UI/UX improvements
For production features: Contribute to the main dashboard after validation here.
This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0) - see the LICENSE file for details.
Why AGPL v3? This license ensures that any modifications remain open source, even when deployed as a web service. This is critical for research transparency - all improvements must be shared with the scientific community.
Mohammad Dastgheib
PhD Candidate, Cognitive Neuroscience
Portfolio: mdastgheib.com
LinkedIn: mohdasti
GitHub: @mohdasti
Production-ready monitoring system for clinical use. Includes:
- Live monitoring with 5Hz updates
- GT live tables with reference ranges
- ML diagnostics suite (6 tabs)
- Calibration analysis
- SHAP explainability
See EMBED_SETUP.md for embedding instructions.
If you use this tool in research or education, please cite:
@software{dastgheib2025traininglab,
author = {Dastgheib, Mohammad},
title = {Surgical Training Lab: Interactive Cognitive Theory Exploration},
year = {2025},
url = {https://github.com/mohdasti/surgical-training-lab},
note = {Research and educational tool for surgical cognitive monitoring}
}"I'm teaching a grad course on attention"
β Use Inverted-U adjuster to demonstrate arousal-performance relationship β
"I'm researching optimal alert thresholds"
β Use Unified Sensitivity to explore liberal vs. conservative strategies β
"I'm studying fatigue in 8-hour surgeries"
β Use Fatigue-Adaptive to model vigilance decrement β
"I want to monitor a live surgery"
β Use the Production Dashboard instead
"I need ML model diagnostics and SHAP plots"
β Use the Production Dashboard instead
This is a research and educational tool. All data is synthetic. Not for clinical use without extensive validation.




