Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,73 +1,197 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
| 2 |
import plotly.graph_objects as go
|
| 3 |
-
import time
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 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 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
)
|
| 43 |
|
| 44 |
return fig
|
| 45 |
|
| 46 |
-
# Button to
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
placeholder = st.empty()
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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']}")
|