Ashar086 commited on
Commit
39149b3
·
verified ·
1 Parent(s): 2d5f252

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -53
app.py CHANGED
@@ -1,73 +1,197 @@
1
  import streamlit as st
 
 
2
  import plotly.graph_objects as go
3
- import time
4
 
5
- # Define the healthcare stages (frames) with corresponding data
6
- stages = [
7
- {"frame": "Stage 1: Initial Diagnosis", "patient_heart_rate": 72, "blood_pressure": "120/80", "status": "Stable"},
8
- {"frame": "Stage 2: Test Results Received", "patient_heart_rate": 75, "blood_pressure": "130/85", "status": "Mild Hypertension"},
9
- {"frame": "Stage 3: Medication Prescribed", "patient_heart_rate": 78, "blood_pressure": "125/80", "status": "Improving"},
10
- {"frame": "Stage 4: Follow-up Visit", "patient_heart_rate": 70, "blood_pressure": "118/78", "status": "Healthy"}
11
- ]
12
 
13
- # Streamlit setup
14
- st.title("Interactive Healthcare Animation")
15
 
16
- # Function to create interactive graph
17
- def create_health_graph(heart_rate, blood_pressure, frame_number):
18
- fig = go.Figure()
19
 
20
- # Heart rate graph
21
- fig.add_trace(go.Indicator(
22
- mode="gauge+number",
23
- value=heart_rate,
24
- title={'text': f"Heart Rate (BPM) - {stages[frame_number]['frame']}"},
25
- domain={'x': [0, 0.5], 'y': [0, 1]}, # Adjusted domain values
26
- gauge={'axis': {'range': [60, 120]}}
27
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- # Blood pressure (represented as systolic value)
30
- systolic_bp = int(blood_pressure.split('/')[0])
31
- fig.add_trace(go.Indicator(
32
- mode="gauge+number",
33
- value=systolic_bp,
34
- title={'text': "Systolic Blood Pressure"},
35
- domain={'x': [0.5, 1], 'y': [0, 1]}, # Adjusted domain values
36
- gauge={'axis': {'range': [90, 180]}}
37
  ))
38
 
 
39
  fig.update_layout(
40
- grid={'rows': 1, 'columns': 2, 'pattern': "independent"},
41
- template='plotly_dark'
 
 
 
 
 
 
 
42
  )
43
 
44
  return fig
45
 
46
- # Button to start the animation
47
- start_button = st.button("Start Animation")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- if start_button:
50
- # Placeholder for dynamic updates
51
- placeholder = st.empty()
52
 
53
- for i in range(len(stages)):
54
- with placeholder.container():
55
- col1, col2 = st.columns([1, 2])
 
 
 
56
 
57
- with col1:
58
- # Display patient status for the current stage
59
- st.subheader(f"{stages[i]['frame']}")
60
- st.write(f"Heart Rate: {stages[i]['patient_heart_rate']} BPM")
61
- st.write(f"Blood Pressure: {stages[i]['blood_pressure']}")
62
- st.write(f"Patient Status: {stages[i]['status']}")
 
63
 
64
- with col2:
65
- # Generate and display the interactive graph
66
- fig = create_health_graph(stages[i]["patient_heart_rate"], stages[i]["blood_pressure"], i)
67
- st.plotly_chart(fig, use_container_width=True)
68
 
69
- # Pause for a short duration before moving to the next frame
70
- time.sleep(2)
71
 
72
- # Display a final summary
73
- st.write("**Animation Complete: Patient's condition has stabilized.**")
 
 
 
 
 
1
  import streamlit as st
2
+ import numpy as np
3
+ import random
4
  import plotly.graph_objects as go
 
5
 
6
+ # Initialize agents (doctors, nurses, clinicians, patients)
7
+ agents = {
8
+ "Doctors": 5,
9
+ "Nurses": 10,
10
+ "Clinicians": 8,
11
+ "Patients": 200
12
+ }
13
 
14
+ # Define states for patients (health conditions)
15
+ patient_conditions = ["Healthy", "Mild Illness", "Chronic Illness", "Emergency"]
16
 
17
+ # Define emotions for healthcare agents (stress, focus, etc.)
18
+ doctor_emotions = ["Calm", "Stressed", "Overwhelmed"]
19
+ nurse_emotions = ["Focused", "Fatigued", "Panicked"]
20
 
21
+ # Define the actions doctors can take
22
+ doctor_actions = ["Prescribe Medication", "Recommend Tests", "Consult Clinician", "Schedule Surgery"]
23
+
24
+ # Define the actions nurses can take
25
+ nurse_actions = ["Monitor Vitals", "Administer Medication", "Report to Doctor", "Assist Surgery"]
26
+
27
+ # Reward and penalty system
28
+ rewards = {
29
+ "Prescribe Medication": 12, # Slightly increased reward
30
+ "Recommend Tests": 7, # Slightly increased reward
31
+ "Consult Clinician": 9,
32
+ "Schedule Surgery": 17,
33
+ "Monitor Vitals": 4,
34
+ "Administer Medication": 12,
35
+ "Review Diagnostic Test": 7,
36
+ "Recommend Additional Tests": 6
37
+ }
38
+
39
+ penalties = {
40
+ "Wrong Medication": -5, # Reduced penalty
41
+ "Missed Diagnosis": -10,
42
+ "Incorrect Test Recommendation": -3,
43
+ "Stress-Induced Mistake": -7
44
+ }
45
+
46
+ # Initialize the session state for counting treatments
47
+ if "performance_metrics" not in st.session_state:
48
+ st.session_state.performance_metrics = {
49
+ "Doctor": {"successful_treatments": 0, "failed_treatments": 0},
50
+ "Nurse": {"successful_assists": 0, "failed_assists": 0}
51
+ }
52
+ if "patient_satisfaction" not in st.session_state:
53
+ st.session_state.patient_satisfaction = 100
54
+
55
+ # Define Reinforcement Learning algorithm (basic Q-learning approach)
56
+ class Agent:
57
+ def __init__(self, agent_type):
58
+ self.agent_type = agent_type
59
+ self.q_table = np.zeros((len(patient_conditions), len(doctor_actions if agent_type == "Doctor" else nurse_actions)))
60
+ self.state = random.choice(patient_conditions)
61
+
62
+ def choose_action(self, exploration_rate=0.03): # Further reduce exploration rate
63
+ if random.uniform(0, 1) < exploration_rate: # Explore
64
+ return random.randint(0, len(doctor_actions)-1 if self.agent_type == "Doctor" else len(nurse_actions)-1)
65
+ else: # Exploit (choose the best action based on Q-values)
66
+ return np.argmax(self.q_table)
67
+
68
+ def update_q_value(self, state, action, reward, learning_rate=0.25, discount_factor=0.95): # Increase learning rate
69
+ old_q_value = self.q_table[state, action]
70
+ best_future_q_value = np.max(self.q_table)
71
+ new_q_value = old_q_value + learning_rate * (reward + discount_factor * best_future_q_value - old_q_value)
72
+ self.q_table[state, action] = new_q_value
73
+
74
+ # Instantiate agents
75
+ doctor_agent = Agent("Doctor")
76
+ nurse_agent = Agent("Nurse")
77
+
78
+ # Animation function
79
+ def create_animation(successful_treatments, failed_treatments):
80
+ fig = go.Figure()
81
 
82
+ # Add traces for successful and failed treatments
83
+ fig.add_trace(go.Bar(
84
+ x=['Successful Treatments', 'Failed Treatments'],
85
+ y=[successful_treatments, failed_treatments],
86
+ marker_color=['green', 'red'],
87
+ name='Doctor Performance'
 
 
88
  ))
89
 
90
+ # Animation settings
91
  fig.update_layout(
92
+ title="Doctor Performance Metrics",
93
+ xaxis_title="Treatment Type",
94
+ yaxis_title="Number of Treatments",
95
+ updatemenus=[dict(type="buttons",
96
+ buttons=[dict(label="Play",
97
+ method="animate",
98
+ args=[None, {"frame": {"duration": 500, "redraw": True}, "fromcurrent": True}])])],
99
+ frames=[go.Frame(data=[go.Bar(y=[successful_treatments + i, failed_treatments + i])], name=str(i))
100
+ for i in range(1, 10)] # Example of dynamic range
101
  )
102
 
103
  return fig
104
 
105
+ # Button to run the simulation
106
+ if st.button("Run Simulation"):
107
+ # Simulate special event (disease outbreak or resource shortage)
108
+ special_event = random.choice([None, "Disease Outbreak", "Resource Shortage"])
109
+ if special_event:
110
+ st.subheader(f"Special Event: {special_event}")
111
+ if special_event == "Disease Outbreak":
112
+ st.write("A sudden disease outbreak has flooded the hospital with new patients. Resources are limited!")
113
+ elif special_event == "Resource Shortage":
114
+ st.write("A medical supply shortage is impacting the hospital. Staff must prioritize high-risk patients.")
115
+
116
+ # Patient Condition Simulation
117
+ patient_state = random.choice(patient_conditions)
118
+ st.write(f"Simulated Patient Condition: {patient_state}")
119
+
120
+ # Random doctor and nurse emotions (affects performance)
121
+ doctor_emotion = random.choice(doctor_emotions)
122
+ nurse_emotion = random.choice(nurse_emotions)
123
+ st.write(f"Doctor's Emotional State: {doctor_emotion}")
124
+ st.write(f"Nurse's Emotional State: {nurse_emotion}")
125
+
126
+ # Doctor Action Simulation
127
+ doctor_action = doctor_agent.choose_action()
128
+ st.write(f"Doctor's Chosen Action: {doctor_actions[doctor_action]}")
129
+
130
+ # Nurse Action Simulation
131
+ nurse_action = nurse_agent.choose_action()
132
+ st.write(f"Nurse's Chosen Action: {nurse_actions[nurse_action]}")
133
+
134
+ # Complications that can arise during treatment
135
+ complication = random.choices(
136
+ [None, "Allergic Reaction", "Unexpected Complication"],
137
+ weights=[0.6, 0.2, 0.2]
138
+ )[0]
139
+
140
+ if complication:
141
+ st.subheader(f"Complication: {complication}")
142
+ if complication == "Allergic Reaction":
143
+ st.write("The patient has developed an allergic reaction to the prescribed medication!")
144
+ penalty = penalties.get("Wrong Medication", 0)
145
+ st.session_state.patient_satisfaction -= 10
146
+ elif complication == "Unexpected Complication":
147
+ st.write("An unexpected complication occurred during surgery!")
148
+ penalty = penalties.get("Stress-Induced Mistake", 0)
149
+ st.session_state.patient_satisfaction -= 15
150
+ else:
151
+ penalty = 0
152
+
153
+ # Ensure action constraints for healthy patients
154
+ if patient_state == "Healthy" and doctor_action == 0: # 0 corresponds to "Prescribe Medication"
155
+ penalty = penalties.get("Wrong Medication", 0)
156
+ st.write("Prescribing medication to a healthy patient is unnecessary! Immediate penalty applied.")
157
+ st.session_state.patient_satisfaction -= 20
158
+
159
+ # Reward or penalty based on action and emotional state
160
+ reward = rewards.get(doctor_actions[doctor_action], 0)
161
+ if doctor_emotion in ["Stressed", "Overwhelmed"]:
162
+ penalty += penalties.get("Stress-Induced Mistake", 0)
163
+
164
+ # Update Q-values
165
+ doctor_agent.update_q_value(patient_conditions.index(patient_state), doctor_action, reward if penalty == 0 else penalty)
166
 
167
+ st.write(f"Doctor's Reward: {reward if penalty == 0 else penalty}")
168
+ st.write(f"Patient Satisfaction: {st.session_state.patient_satisfaction}")
 
169
 
170
+ # Simulated patient feedback and next steps
171
+ next_step = random.choices(
172
+ ["Recovery", "Further Treatment Needed", "Complication"],
173
+ weights=[0.6, 0.3, 0.1]
174
+ )[0]
175
+ st.write(f"Patient Status after treatment: {next_step}")
176
 
177
+ # Increment performance based on outcome
178
+ if next_step == "Recovery":
179
+ st.session_state.performance_metrics["Doctor"]["successful_treatments"] += 1
180
+ st.session_state.performance_metrics["Nurse"]["successful_assists"] += 1
181
+ else:
182
+ st.session_state.performance_metrics["Doctor"]["failed_treatments"] += 1
183
+ st.session_state.performance_metrics["Nurse"]["failed_assists"] += 1
184
 
185
+ # Create animation for performance metrics
186
+ successful_treatments = st.session_state.performance_metrics["Doctor"]["successful_treatments"]
187
+ failed_treatments = st.session_state.performance_metrics["Doctor"]["failed_treatments"]
 
188
 
189
+ fig = create_animation(successful_treatments, failed_treatments)
190
+ st.plotly_chart(fig)
191
 
192
+ # Display performance metrics
193
+ st.subheader("Performance Metrics:")
194
+ st.write(f"Doctor's Successful Treatments: {st.session_state.performance_metrics['Doctor']['successful_treatments']}")
195
+ st.write(f"Doctor's Failed Treatments: {st.session_state.performance_metrics['Doctor']['failed_treatments']}")
196
+ st.write(f"Nurse's Successful Assists: {st.session_state.performance_metrics['Nurse']['successful_assists']}")
197
+ st.write(f"Nurse's Failed Assists: {st.session_state.performance_metrics['Nurse']['failed_assists']}")