Ashar086 commited on
Commit
b223c89
·
verified ·
1 Parent(s): e1f4bfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -106
app.py CHANGED
@@ -1,49 +1,30 @@
1
  import streamlit as st
2
  import numpy as np
3
  import random
4
- import time # For animation delays
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,
30
  "Recommend Tests": 7,
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,
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},
@@ -52,119 +33,121 @@ if "performance_metrics" not in st.session_state:
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):
63
- if random.uniform(0, 1) < exploration_rate:
64
- return random.randint(0, len(doctor_actions)-1 if self.agent_type == "Doctor" else len(nurse_actions)-1)
65
- else:
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):
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 for smoother transitions
79
- def animate_text(text, delay=0.1):
80
- for char in text:
81
- st.write(char, end="")
82
- time.sleep(delay)
83
- st.write("\n")
84
 
85
- # Button to run the simulation
86
- if st.button("Run Simulation"):
87
- st.subheader("Simulation Running...")
88
-
89
- # Simulate special event (disease outbreak or resource shortage)
90
- special_event = random.choice([None, "Disease Outbreak", "Resource Shortage"])
91
- if special_event:
92
- animate_text(f"Special Event: {special_event}")
93
- if special_event == "Disease Outbreak":
94
- animate_text("A sudden disease outbreak has flooded the hospital with new patients. Resources are limited!")
95
- elif special_event == "Resource Shortage":
96
- animate_text("A medical supply shortage is impacting the hospital. Staff must prioritize high-risk patients.")
97
-
98
- # Patient Condition Simulation
99
- patient_state = random.choice(patient_conditions)
100
- animate_text(f"Simulated Patient Condition: {patient_state}")
101
-
102
- # Random doctor and nurse emotions (affects performance)
103
- doctor_emotion = random.choice(doctor_emotions)
104
- nurse_emotion = random.choice(nurse_emotions)
105
- animate_text(f"Doctor's Emotional State: {doctor_emotion}")
106
- animate_text(f"Nurse's Emotional State: {nurse_emotion}")
107
-
108
- # Doctor Action Simulation
109
- doctor_action = doctor_agent.choose_action()
110
- animate_text(f"Doctor's Chosen Action: {doctor_actions[doctor_action]}")
111
-
112
- # Nurse Action Simulation
113
- nurse_action = nurse_agent.choose_action()
114
- animate_text(f"Nurse's Chosen Action: {nurse_actions[nurse_action]}")
115
-
116
- # Complications that can arise during treatment
117
  complication = random.choices(
118
  [None, "Allergic Reaction", "Unexpected Complication"],
119
  weights=[0.6, 0.2, 0.2]
120
  )[0]
121
 
 
122
  if complication:
123
- animate_text(f"Complication: {complication}")
124
  if complication == "Allergic Reaction":
125
- animate_text("The patient has developed an allergic reaction to the prescribed medication!")
126
- penalty = penalties.get("Wrong Medication", 0)
127
  st.session_state.patient_satisfaction -= 10
128
  elif complication == "Unexpected Complication":
129
- animate_text("An unexpected complication occurred during surgery!")
130
- penalty = penalties.get("Stress-Induced Mistake", 0)
131
  st.session_state.patient_satisfaction -= 15
132
- else:
133
- penalty = 0
134
 
135
- # Ensure action constraints for healthy patients
136
- if patient_state == "Healthy" and doctor_action == 0:
137
- penalty = penalties.get("Wrong Medication", 0)
138
- animate_text("Prescribing medication to a healthy patient is unnecessary! Immediate penalty applied.")
139
- st.session_state.patient_satisfaction -= 20
140
 
141
- # Reward or penalty based on action and emotional state
142
- reward = rewards.get(doctor_actions[doctor_action], 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  if doctor_emotion in ["Stressed", "Overwhelmed"]:
144
- penalty += penalties.get("Stress-Induced Mistake", 0)
145
-
146
  # Update Q-values
147
- doctor_agent.update_q_value(patient_conditions.index(patient_state), doctor_action, reward if penalty == 0 else penalty)
148
-
149
- animate_text(f"Doctor's Reward: {reward if penalty == 0 else penalty}")
150
- animate_text(f"Patient Satisfaction: {st.session_state.patient_satisfaction}")
151
-
152
- # Simulated patient feedback and next steps
153
- next_step = random.choices(
154
  ["Recovery", "Further Treatment Needed", "Complication"],
155
  weights=[0.6, 0.3, 0.1]
156
  )[0]
157
- animate_text(f"Patient Status after treatment: {next_step}")
158
-
159
- # Increment performance based on outcome
160
- if next_step == "Recovery":
161
  st.session_state.performance_metrics["Doctor"]["successful_treatments"] += 1
162
  st.session_state.performance_metrics["Nurse"]["successful_assists"] += 1
163
  else:
164
  st.session_state.performance_metrics["Doctor"]["failed_treatments"] += 1
165
  st.session_state.performance_metrics["Nurse"]["failed_assists"] += 1
166
 
167
- st.write("Simulation completed! Click 'Run Simulation' again to simulate different actions and outcomes.")
168
 
169
  # Display performance metrics
170
  st.subheader("Performance Metrics:")
 
1
  import streamlit as st
2
  import numpy as np
3
  import random
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Initialize constants
6
+ DOCTOR_ACTIONS = ["Prescribe Medication", "Recommend Tests", "Consult Clinician", "Schedule Surgery"]
7
+ NURSE_ACTIONS = ["Monitor Vitals", "Administer Medication", "Report to Doctor", "Assist Surgery"]
8
+ PATIENT_CONDITIONS = ["Healthy", "Mild Illness", "Chronic Illness", "Emergency"]
9
+ DOCTOR_EMOTIONS = ["Calm", "Stressed", "Overwhelmed"]
10
+ NURSE_EMOTIONS = ["Focused", "Fatigued", "Panicked"]
11
 
12
+ # Rewards and Penalties
13
+ REWARDS = {
14
  "Prescribe Medication": 12,
15
  "Recommend Tests": 7,
16
  "Consult Clinician": 9,
17
  "Schedule Surgery": 17,
18
  "Monitor Vitals": 4,
19
  "Administer Medication": 12,
 
 
20
  }
21
+ PENALTIES = {
 
22
  "Wrong Medication": -5,
23
  "Missed Diagnosis": -10,
24
+ "Stress-Induced Mistake": -7,
 
25
  }
26
 
27
+ # Initialize session state for metrics and satisfaction
28
  if "performance_metrics" not in st.session_state:
29
  st.session_state.performance_metrics = {
30
  "Doctor": {"successful_treatments": 0, "failed_treatments": 0},
 
33
  if "patient_satisfaction" not in st.session_state:
34
  st.session_state.patient_satisfaction = 100
35
 
36
+
37
+ # Define the Agent class for Q-learning
38
  class Agent:
39
  def __init__(self, agent_type):
40
  self.agent_type = agent_type
41
+ self.actions = DOCTOR_ACTIONS if agent_type == "Doctor" else NURSE_ACTIONS
42
+ self.q_table = np.zeros((len(PATIENT_CONDITIONS), len(self.actions)))
43
 
44
+ def choose_action(self, state, exploration_rate=0.05):
45
+ if random.uniform(0, 1) < exploration_rate: # Explore
46
+ return random.randint(0, len(self.actions)-1)
47
+ else: # Exploit (choose best action)
48
+ return np.argmax(self.q_table[state])
49
+
50
+ def update_q_value(self, state, action, reward, learning_rate=0.1, discount_factor=0.9):
51
  old_q_value = self.q_table[state, action]
52
  best_future_q_value = np.max(self.q_table)
53
  new_q_value = old_q_value + learning_rate * (reward + discount_factor * best_future_q_value - old_q_value)
54
  self.q_table[state, action] = new_q_value
55
 
56
+
57
  # Instantiate agents
58
  doctor_agent = Agent("Doctor")
59
  nurse_agent = Agent("Nurse")
60
 
 
 
 
 
 
 
61
 
62
+ # Function to simulate a special event
63
+ def simulate_special_event():
64
+ event = random.choice([None, "Disease Outbreak", "Resource Shortage"])
65
+ if event == "Disease Outbreak":
66
+ st.subheader("Special Event: Disease Outbreak")
67
+ st.write("A sudden disease outbreak has flooded the hospital with new patients. Resources are limited!")
68
+ elif event == "Resource Shortage":
69
+ st.subheader("Special Event: Resource Shortage")
70
+ st.write("A medical supply shortage is impacting the hospital. Staff must prioritize high-risk patients.")
71
+ return event
72
+
73
+
74
+ # Function to handle complications during treatment
75
+ def handle_complications():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  complication = random.choices(
77
  [None, "Allergic Reaction", "Unexpected Complication"],
78
  weights=[0.6, 0.2, 0.2]
79
  )[0]
80
 
81
+ penalty = 0
82
  if complication:
83
+ st.subheader(f"Complication: {complication}")
84
  if complication == "Allergic Reaction":
85
+ st.write("The patient has developed an allergic reaction to the prescribed medication!")
86
+ penalty = PENALTIES["Wrong Medication"]
87
  st.session_state.patient_satisfaction -= 10
88
  elif complication == "Unexpected Complication":
89
+ st.write("An unexpected complication occurred during surgery!")
90
+ penalty = PENALTIES["Stress-Induced Mistake"]
91
  st.session_state.patient_satisfaction -= 15
92
+ return penalty
 
93
 
 
 
 
 
 
94
 
95
+ # Main simulation button logic
96
+ if st.button("Run Simulation"):
97
+ # Simulate a special event
98
+ special_event = simulate_special_event()
99
+
100
+ # Patient condition simulation
101
+ patient_state = random.choice(PATIENT_CONDITIONS)
102
+ st.write(f"Simulated Patient Condition: {patient_state}")
103
+ patient_index = PATIENT_CONDITIONS.index(patient_state)
104
+
105
+ # Doctor and nurse emotions
106
+ doctor_emotion = random.choice(DOCTOR_EMOTIONS)
107
+ nurse_emotion = random.choice(NURSE_EMOTIONS)
108
+ st.write(f"Doctor's Emotional State: {doctor_emotion}")
109
+ st.write(f"Nurse's Emotional State: {nurse_emotion}")
110
+
111
+ # Doctor Action
112
+ doctor_action_index = doctor_agent.choose_action(patient_index)
113
+ doctor_action = DOCTOR_ACTIONS[doctor_action_index]
114
+ st.write(f"Doctor's Chosen Action: {doctor_action}")
115
+
116
+ # Nurse Action
117
+ nurse_action_index = nurse_agent.choose_action(patient_index)
118
+ nurse_action = NURSE_ACTIONS[nurse_action_index]
119
+ st.write(f"Nurse's Chosen Action: {nurse_action}")
120
+
121
+ # Handle potential complications
122
+ penalty = handle_complications()
123
+
124
+ # Reward or penalty
125
+ reward = REWARDS.get(doctor_action, 0) if penalty == 0 else penalty
126
  if doctor_emotion in ["Stressed", "Overwhelmed"]:
127
+ penalty += PENALTIES["Stress-Induced Mistake"]
128
+
129
  # Update Q-values
130
+ doctor_agent.update_q_value(patient_index, doctor_action_index, reward)
131
+
132
+ st.write(f"Doctor's Reward/Penalty: {reward}")
133
+ st.write(f"Patient Satisfaction: {st.session_state.patient_satisfaction}")
134
+
135
+ # Outcome and Performance Metrics Update
136
+ outcome = random.choices(
137
  ["Recovery", "Further Treatment Needed", "Complication"],
138
  weights=[0.6, 0.3, 0.1]
139
  )[0]
140
+
141
+ st.write(f"Patient Status after Treatment: {outcome}")
142
+
143
+ if outcome == "Recovery":
144
  st.session_state.performance_metrics["Doctor"]["successful_treatments"] += 1
145
  st.session_state.performance_metrics["Nurse"]["successful_assists"] += 1
146
  else:
147
  st.session_state.performance_metrics["Doctor"]["failed_treatments"] += 1
148
  st.session_state.performance_metrics["Nurse"]["failed_assists"] += 1
149
 
150
+ st.write("Simulation completed! Run again for different outcomes.")
151
 
152
  # Display performance metrics
153
  st.subheader("Performance Metrics:")