Download src/apps/educa/services/simulation_training.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 22.2 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/educa/services/simulation_training.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/apps/educa/services/simulation_training.py
-
curl -L -o simulation_training.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/educa/services/simulation_training.py
22.2 kB
| """ | |
| Educa Module - Simulation Training Service | |
| Medical simulation training, virtual reality scenarios, procedural skills development, | |
| and debriefing analytics for clinical education. | |
| Standards Compliance: | |
| - Society for Simulation in Healthcare (SSH) Accreditation | |
| - International Nursing Association for Clinical Simulation and Learning (INACSL) Standards | |
| - American College of Surgeons (ACS) Simulation-Based Surgical Training | |
| - Healthcare Simulation Dictionary (SSH) | |
| - Kirkpatrick Model for Simulation Effectiveness | |
| - PEARLS Debriefing Framework | |
| Features: | |
| - High-fidelity simulation scenarios | |
| - Virtual reality (VR) training modules | |
| - Procedural skills assessment | |
| - Crisis resource management (CRM) | |
| - Team-based simulation | |
| - Structured debriefing | |
| - Performance analytics | |
| - Mastery learning pathways | |
| """ | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timedelta | |
| from enum import Enum | |
| from typing import Any, Dict, List, Optional | |
| import structlog | |
| logger = structlog.get_logger(__name__) | |
| class SimulationType(Enum): | |
| """Types of simulation modalities""" | |
| HIGH_FIDELITY_MANNEQUIN = "high_fidelity_mannequin" | |
| TASK_TRAINER = "task_trainer" # Part-task trainers | |
| VIRTUAL_REALITY = "virtual_reality" | |
| AUGMENTED_REALITY = "augmented_reality" | |
| STANDARDIZED_PATIENT = "standardized_patient" | |
| HYBRID = "hybrid" # Combination | |
| SCREEN_BASED = "screen_based" | |
| class SimulationComplexity(Enum): | |
| """Scenario complexity levels""" | |
| BASIC = "basic" # Single system, straightforward | |
| INTERMEDIATE = "intermediate" # Multiple systems, moderate challenge | |
| ADVANCED = "advanced" # Complex, multiple interventions | |
| EXPERT = "expert" # Rare cases, high stakes | |
| class LearningDomain(Enum): | |
| """Primary learning focus""" | |
| TECHNICAL_SKILLS = "technical_skills" # Procedures | |
| CLINICAL_REASONING = "clinical_reasoning" # Diagnosis | |
| COMMUNICATION = "communication" # Patient/team communication | |
| TEAMWORK = "teamwork" # CRM, collaboration | |
| LEADERSHIP = "leadership" # Team leadership | |
| SYSTEMS_THINKING = "systems_thinking" # Process improvement | |
| class DebriefingModel(Enum): | |
| """Debriefing frameworks""" | |
| PEARLS = "pearls" # Promoting Excellence and Reflective Learning | |
| DASH = "dash" # Debriefing Assessment for Simulation in Healthcare | |
| PLUS_DELTA = "plus_delta" # What went well / what to change | |
| ADVOCACY_INQUIRY = "advocacy_inquiry" # Frame-advocate-inquire | |
| class SimulationScenario: | |
| """Simulation scenario design""" | |
| scenario_id: str | |
| title: str | |
| description: str | |
| simulation_type: SimulationType | |
| complexity: SimulationComplexity | |
| learning_domain: LearningDomain | |
| duration_minutes: int | |
| learning_objectives: List[str] = field(default_factory=list) | |
| prerequisites: List[str] = field(default_factory=list) | |
| equipment_required: List[str] = field(default_factory=list) | |
| scenario_script: str = "" | |
| expected_actions: List[str] = field(default_factory=list) | |
| critical_actions: List[str] = field(default_factory=list) # Must perform | |
| common_errors: List[str] = field(default_factory=list) | |
| class SimulationSession: | |
| """Completed simulation session""" | |
| session_id: str | |
| scenario_id: str | |
| participants: List[str] = field(default_factory=list) # Learner IDs | |
| facilitator_id: str = "" | |
| date: datetime = field(default_factory=datetime.now) | |
| duration_actual_minutes: int = 0 | |
| video_recorded: bool = False | |
| video_url: Optional[str] = None | |
| performance_scores: Dict[str, float] = field(default_factory=dict) # Participant -> score | |
| critical_actions_completed: Dict[str, List[str]] = field(default_factory=dict) | |
| errors_committed: List[str] = field(default_factory=list) | |
| debriefing_completed: bool = False | |
| class PerformanceMetric: | |
| """Individual performance metrics""" | |
| metric_id: str | |
| session_id: str | |
| participant_id: str | |
| technical_score: float = 0.0 # 0-10 scale | |
| clinical_reasoning_score: float = 0.0 | |
| communication_score: float = 0.0 | |
| teamwork_score: float = 0.0 | |
| time_to_recognition: Optional[int] = None # Seconds | |
| time_to_intervention: Optional[int] = None | |
| critical_actions_percentage: float = 0.0 | |
| errors_count: int = 0 | |
| class DebriefingSession: | |
| """Structured debriefing""" | |
| debriefing_id: str | |
| simulation_session_id: str | |
| facilitator_id: str | |
| model: DebriefingModel | |
| start_time: datetime | |
| duration_minutes: int | |
| reactions_phase: List[str] = field(default_factory=list) # Learner reactions | |
| analysis_phase: List[str] = field(default_factory=list) # What happened | |
| summary_phase: List[str] = field(default_factory=list) # Key learnings | |
| action_items: List[str] = field(default_factory=list) | |
| learner_insights: List[str] = field(default_factory=list) | |
| class ProceduralSkill: | |
| """Procedural skill definition""" | |
| skill_id: str | |
| procedure_name: str | |
| specialty: str | |
| difficulty_level: SimulationComplexity | |
| required_attempts_for_mastery: int = 10 | |
| critical_steps: List[str] = field(default_factory=list) | |
| common_pitfalls: List[str] = field(default_factory=list) | |
| assessment_checklist: List[Dict[str, Any]] = field(default_factory=list) | |
| class SkillAttempt: | |
| """Individual skill practice attempt""" | |
| attempt_id: str | |
| learner_id: str | |
| skill_id: str | |
| date: datetime | |
| successful: bool | |
| time_seconds: int | |
| steps_completed: List[str] = field(default_factory=list) | |
| errors: List[str] = field(default_factory=list) | |
| assessor_feedback: str = "" | |
| mastery_achieved: bool = False | |
| class SimulationTrainingService: | |
| """ | |
| Simulation Training Service | |
| Manages medical simulation training, VR scenarios, procedural skills, | |
| and structured debriefing for experiential learning. | |
| """ | |
| def __init__(self): | |
| self.scenarios: Dict[str, SimulationScenario] = {} | |
| self.sessions: Dict[str, SimulationSession] = {} | |
| self.debriefings: Dict[str, DebriefingSession] = {} | |
| self.performance_metrics: Dict[str, PerformanceMetric] = {} | |
| self.procedural_skills: Dict[str, ProceduralSkill] = {} | |
| self.skill_attempts: Dict[str, SkillAttempt] = {} | |
| def create_scenario( | |
| self, | |
| title: str, | |
| description: str, | |
| simulation_type: SimulationType, | |
| complexity: SimulationComplexity, | |
| learning_domain: LearningDomain, | |
| duration_minutes: int, | |
| learning_objectives: List[str], | |
| critical_actions: List[str] | |
| ) -> SimulationScenario: | |
| """Create simulation scenario""" | |
| scenario_id = f"SIM-{datetime.now().strftime('%Y%m%d%H%M%S')}" | |
| scenario = SimulationScenario( | |
| scenario_id=scenario_id, | |
| title=title, | |
| description=description, | |
| simulation_type=simulation_type, | |
| complexity=complexity, | |
| learning_domain=learning_domain, | |
| duration_minutes=duration_minutes, | |
| learning_objectives=learning_objectives, | |
| critical_actions=critical_actions, | |
| prerequisites=[], | |
| equipment_required=[], | |
| scenario_script="", | |
| expected_actions=[], | |
| common_errors=[] | |
| ) | |
| self.scenarios[scenario_id] = scenario | |
| logger.info("created_simulation_scenario", scenario_id=scenario_id, title=title) | |
| return scenario | |
| def run_simulation( | |
| self, | |
| scenario_id: str, | |
| participants: List[str], | |
| facilitator_id: str, | |
| video_recorded: bool = True | |
| ) -> SimulationSession: | |
| """Execute simulation session""" | |
| if scenario_id not in self.scenarios: | |
| raise ValueError(f"Scenario {scenario_id} not found") | |
| scenario = self.scenarios[scenario_id] | |
| session_id = f"SES-{datetime.now().strftime('%Y%m%d%H%M%S')}" | |
| session = SimulationSession( | |
| session_id=session_id, | |
| scenario_id=scenario_id, | |
| participants=participants, | |
| facilitator_id=facilitator_id, | |
| date=datetime.now(), | |
| duration_actual_minutes=scenario.duration_minutes, | |
| video_recorded=video_recorded, | |
| video_url=f"https://simulation-videos.yaz.care/{session_id}" if video_recorded else None, | |
| performance_scores={}, | |
| critical_actions_completed={p: [] for p in participants}, | |
| errors_committed=[], | |
| debriefing_completed=False | |
| ) | |
| self.sessions[session_id] = session | |
| logger.info(f"Started simulation session {session_id} with {len(participants)} participants") | |
| return session | |
| def record_performance( | |
| self, | |
| session_id: str, | |
| participant_id: str, | |
| technical_score: float, | |
| clinical_reasoning_score: float, | |
| communication_score: float, | |
| teamwork_score: float, | |
| time_to_recognition: Optional[int] = None, | |
| time_to_intervention: Optional[int] = None, | |
| critical_actions_completed: Optional[List[str]] = None, | |
| errors_count: int = 0 | |
| ) -> PerformanceMetric: | |
| """Record participant performance metrics""" | |
| if session_id not in self.sessions: | |
| raise ValueError(f"Session {session_id} not found") | |
| session = self.sessions[session_id] | |
| scenario = self.scenarios.get(session.scenario_id) | |
| # Calculate critical actions percentage | |
| if critical_actions_completed and scenario: | |
| total_critical = len(scenario.critical_actions) | |
| completed_critical = len(critical_actions_completed) | |
| critical_percentage = (completed_critical / total_critical * 100) if total_critical > 0 else 0 | |
| else: | |
| critical_percentage = 0.0 | |
| metric_id = f"PERF-{session_id}-{participant_id}" | |
| metric = PerformanceMetric( | |
| metric_id=metric_id, | |
| session_id=session_id, | |
| participant_id=participant_id, | |
| technical_score=technical_score, | |
| clinical_reasoning_score=clinical_reasoning_score, | |
| communication_score=communication_score, | |
| teamwork_score=teamwork_score, | |
| time_to_recognition=time_to_recognition, | |
| time_to_intervention=time_to_intervention, | |
| critical_actions_percentage=critical_percentage, | |
| errors_count=errors_count | |
| ) | |
| self.performance_metrics[metric_id] = metric | |
| # Update session | |
| overall_score = ( | |
| technical_score + clinical_reasoning_score + | |
| communication_score + teamwork_score | |
| ) / 4 | |
| session.performance_scores[participant_id] = overall_score | |
| if critical_actions_completed: | |
| session.critical_actions_completed[participant_id] = critical_actions_completed | |
| logger.info("recorded_performance_for_in_session", participant_id=participant_id, session_id=session_id) | |
| return metric | |
| def conduct_debriefing( | |
| self, | |
| session_id: str, | |
| facilitator_id: str, | |
| model: DebriefingModel, | |
| duration_minutes: int, | |
| learner_insights: List[str], | |
| action_items: List[str] | |
| ) -> DebriefingSession: | |
| """Conduct structured debriefing""" | |
| if session_id not in self.sessions: | |
| raise ValueError(f"Session {session_id} not found") | |
| debriefing_id = f"DEB-{datetime.now().strftime('%Y%m%d%H%M%S')}" | |
| debriefing = DebriefingSession( | |
| debriefing_id=debriefing_id, | |
| simulation_session_id=session_id, | |
| facilitator_id=facilitator_id, | |
| model=model, | |
| start_time=datetime.now(), | |
| duration_minutes=duration_minutes, | |
| reactions_phase=[], | |
| analysis_phase=[], | |
| summary_phase=[], | |
| action_items=action_items, | |
| learner_insights=learner_insights | |
| ) | |
| self.debriefings[debriefing_id] = debriefing | |
| # Mark session as debriefed | |
| self.sessions[session_id].debriefing_completed = True | |
| logger.info("completed_debriefing_for_session", debriefing_id=debriefing_id, session_id=session_id) | |
| return debriefing | |
| def define_procedural_skill( | |
| self, | |
| procedure_name: str, | |
| specialty: str, | |
| difficulty_level: SimulationComplexity, | |
| critical_steps: List[str], | |
| required_attempts: int = 10 | |
| ) -> ProceduralSkill: | |
| """Define procedural skill for mastery learning""" | |
| skill_id = f"PROC-{datetime.now().strftime('%Y%m%d%H%M%S')}" | |
| # Create assessment checklist from critical steps | |
| checklist = [ | |
| { | |
| 'step': step, | |
| 'critical': True, | |
| 'max_attempts': 3 | |
| } | |
| for step in critical_steps | |
| ] | |
| skill = ProceduralSkill( | |
| skill_id=skill_id, | |
| procedure_name=procedure_name, | |
| specialty=specialty, | |
| difficulty_level=difficulty_level, | |
| required_attempts_for_mastery=required_attempts, | |
| critical_steps=critical_steps, | |
| common_pitfalls=[], | |
| assessment_checklist=checklist | |
| ) | |
| self.procedural_skills[skill_id] = skill | |
| logger.info("defined_procedural_skill", skill_id=skill_id, procedure_name=procedure_name) | |
| return skill | |
| def record_skill_attempt( | |
| self, | |
| learner_id: str, | |
| skill_id: str, | |
| successful: bool, | |
| time_seconds: int, | |
| steps_completed: List[str], | |
| errors: List[str], | |
| assessor_feedback: str = "" | |
| ) -> SkillAttempt: | |
| """Record procedural skill practice attempt""" | |
| if skill_id not in self.procedural_skills: | |
| raise ValueError(f"Skill {skill_id} not found") | |
| skill = self.procedural_skills[skill_id] | |
| attempt_id = f"ATT-{datetime.now().strftime('%Y%m%d%H%M%S')}" | |
| # Check for mastery | |
| learner_attempts = [ | |
| att for att in self.skill_attempts.values() | |
| if att.learner_id == learner_id and att.skill_id == skill_id | |
| ] | |
| consecutive_successes = 0 | |
| for attempt in reversed(learner_attempts): | |
| if attempt.successful: | |
| consecutive_successes += 1 | |
| else: | |
| break | |
| # Mastery = required consecutive successful attempts | |
| mastery_achieved = ( | |
| consecutive_successes + (1 if successful else 0) >= skill.required_attempts_for_mastery | |
| ) | |
| attempt = SkillAttempt( | |
| attempt_id=attempt_id, | |
| learner_id=learner_id, | |
| skill_id=skill_id, | |
| date=datetime.now(), | |
| successful=successful, | |
| time_seconds=time_seconds, | |
| steps_completed=steps_completed, | |
| errors=errors, | |
| assessor_feedback=assessor_feedback, | |
| mastery_achieved=mastery_achieved | |
| ) | |
| self.skill_attempts[attempt_id] = attempt | |
| if mastery_achieved: | |
| logger.info("learner_achieved_mastery_of_skill", learner_id=learner_id, skill_id=skill_id) | |
| return attempt | |
| def get_learner_simulation_history( | |
| self, | |
| learner_id: str | |
| ) -> Dict[str, Any]: | |
| """Get learner's simulation training history""" | |
| # Find all sessions | |
| learner_sessions = [ | |
| session for session in self.sessions.values() | |
| if learner_id in session.participants | |
| ] | |
| if not learner_sessions: | |
| return { | |
| 'learner_id': learner_id, | |
| 'total_sessions': 0, | |
| 'message': 'No simulation history found' | |
| } | |
| # Performance metrics | |
| learner_metrics = [ | |
| metric for metric in self.performance_metrics.values() | |
| if metric.participant_id == learner_id | |
| ] | |
| # Calculate averages | |
| if learner_metrics: | |
| avg_technical = sum(m.technical_score for m in learner_metrics) / len(learner_metrics) | |
| avg_reasoning = sum(m.clinical_reasoning_score for m in learner_metrics) / len(learner_metrics) | |
| avg_communication = sum(m.communication_score for m in learner_metrics) / len(learner_metrics) | |
| avg_teamwork = sum(m.teamwork_score for m in learner_metrics) / len(learner_metrics) | |
| else: | |
| avg_technical = avg_reasoning = avg_communication = avg_teamwork = 0.0 | |
| # Debriefings attended | |
| debriefed_sessions = sum(1 for s in learner_sessions if s.debriefing_completed) | |
| # Procedural skills | |
| learner_skill_attempts = [ | |
| att for att in self.skill_attempts.values() | |
| if att.learner_id == learner_id | |
| ] | |
| skills_mastered = len(set( | |
| att.skill_id for att in learner_skill_attempts if att.mastery_achieved | |
| )) | |
| history = { | |
| 'learner_id': learner_id, | |
| 'total_sessions': len(learner_sessions), | |
| 'debriefings_completed': debriefed_sessions, | |
| 'average_performance': { | |
| 'technical_skills': avg_technical, | |
| 'clinical_reasoning': avg_reasoning, | |
| 'communication': avg_communication, | |
| 'teamwork': avg_teamwork, | |
| 'overall': (avg_technical + avg_reasoning + avg_communication + avg_teamwork) / 4 | |
| }, | |
| 'procedural_skills': { | |
| 'total_attempts': len(learner_skill_attempts), | |
| 'skills_mastered': skills_mastered | |
| }, | |
| 'recent_sessions': [ | |
| { | |
| 'session_id': s.session_id, | |
| 'scenario': self.scenarios.get(s.scenario_id).title if s.scenario_id in self.scenarios else 'Unknown', # type: ignore[union-attr] | |
| 'date': s.date, | |
| 'score': s.performance_scores.get(learner_id, 0.0) | |
| } | |
| for s in sorted(learner_sessions, key=lambda x: x.date, reverse=True)[:5] | |
| ] | |
| } | |
| return history | |
| def analyze_simulation_effectiveness( | |
| self, | |
| scenario_id: str | |
| ) -> Dict[str, Any]: | |
| """Analyze scenario effectiveness across sessions""" | |
| if scenario_id not in self.scenarios: | |
| raise ValueError(f"Scenario {scenario_id} not found") | |
| scenario = self.scenarios[scenario_id] | |
| # Find all sessions for this scenario | |
| scenario_sessions = [ | |
| s for s in self.sessions.values() | |
| if s.scenario_id == scenario_id | |
| ] | |
| if not scenario_sessions: | |
| return { | |
| 'scenario_id': scenario_id, | |
| 'message': 'No sessions completed for this scenario' | |
| } | |
| # Collect all performance metrics | |
| all_metrics = [ | |
| metric for session in scenario_sessions | |
| for metric in self.performance_metrics.values() | |
| if metric.session_id == session.session_id | |
| ] | |
| if not all_metrics: | |
| return { | |
| 'scenario_id': scenario_id, | |
| 'sessions_completed': len(scenario_sessions), | |
| 'message': 'No performance data available' | |
| } | |
| # Calculate statistics | |
| avg_technical = sum(m.technical_score for m in all_metrics) / len(all_metrics) | |
| avg_reasoning = sum(m.clinical_reasoning_score for m in all_metrics) / len(all_metrics) | |
| avg_critical_actions = sum(m.critical_actions_percentage for m in all_metrics) / len(all_metrics) | |
| # Common errors across sessions | |
| all_errors = [] | |
| for session in scenario_sessions: | |
| all_errors.extend(session.errors_committed) | |
| error_frequency = {} # type: ignore[name-defined, index, return-value, var-annotated] | |
| for error in all_errors: | |
| error_frequency[error] = error_frequency.get(error, 0) + 1 | |
| common_errors = sorted( | |
| error_frequency.items(), | |
| key=lambda x: x[1], | |
| reverse=True | |
| )[:5] | |
| analysis = { | |
| 'scenario_id': scenario_id, | |
| 'scenario_title': scenario.title, | |
| 'complexity': scenario.complexity.value, | |
| 'sessions_completed': len(scenario_sessions), | |
| 'total_participants': sum(len(s.participants) for s in scenario_sessions), | |
| 'average_performance': { | |
| 'technical_skills': avg_technical, | |
| 'clinical_reasoning': avg_reasoning, | |
| 'critical_actions_completion': avg_critical_actions | |
| }, | |
| 'common_errors': [{'error': err, 'frequency': freq} for err, freq in common_errors], | |
| 'debriefing_rate': sum(1 for s in scenario_sessions if s.debriefing_completed) / len(scenario_sessions) * 100, | |
| 'recommendations': [] | |
| } | |
| # Generate recommendations | |
| if avg_critical_actions < 80.0: | |
| analysis['recommendations'].append("Consider simplifying critical actions or providing more pre-briefing") # type: ignore[arg-type, union-attr] | |
| if analysis['debriefing_rate'] < 90.0: # type: ignore[misc, operator, valid-type] | |
| analysis['recommendations'].append("Ensure consistent debriefing for all sessions") # type: ignore[arg-type, union-attr] | |
| if len(common_errors) > 0: | |
| analysis['recommendations'].append(f"Focus teaching on common error: {common_errors[0][0]}") # type: ignore[arg-type, union-attr] | |
| return analysis | |