python
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
from datetime import datetime, timedelta
import io
# Set page config
st.set_page_config(page_title="Hospital AMS Cockpit", layout="wide", page_icon="🏥")
# Custom CSS for better styling
st.markdown("""
<style>
.metric-card { background-color: #f0f2f6; padding: 1rem; border-radius: 10px; border-left: 5px solid #1f77b4; }
.alert-card { background-color: #fff3cd; padding: 1rem; border-radius: 10px; border-left: 5px solid #ffc107; }
</style>
""", unsafe_allow_html=True)
@st.cache_data
def load_synthetic_data():
"""
Generate synthetic hospital data for AMS analytics.
Columns:
- patient_id: Unique patient ID
- admission_date: Date admitted
- discharge_date: Date discharged
- ward: Ward name
- culture_date: Date of culture collection
- pathogen: Isolated bug (e.g., 'E. coli', 'MRSA')
- susceptibility: Susceptibility profile (dict-like string, e.g., 'Cefepime:S, Piperacillin:S')
- drug_prescribed: Antibiotic prescribed (e.g., 'Vancomycin', 'Meropenem')
- drug_start: Start date of therapy
- drug_end: End date of therapy
- ddd: Defined Daily Dose (WHO standard)
"""
np.random.seed(42)
n_patients = 500
wards = ['ICU', 'Surgical', 'Medical', 'Pediatric']
pathogens = ['E. coli', 'Klebsiella spp.', 'Pseudomonas aeruginosa', 'MRSA', 'Candida albicans', 'Enterococcus faecium']
antibiotics = ['Vancomycin', 'Meropenem', 'Piperacillin-Tazobactam', 'Cefepime', 'Ceftriaxone', 'Levofloxacin', 'Amoxicillin-Clavulanate']
ddd_dict = {
'Vancomycin': 2.0, 'Meropenem': 2.0, 'Piperacillin-Tazobactam': 13.5, 'Cefepime': 2.0,
'Ceftriaxone': 2.0, 'Levofloxacin': 0.5, 'Amoxicillin-Clavulanate': 2.0
}
data = []
start_date = datetime(2023, 1, 1)
for i in range(n_patients):
adm_date = start_date + timedelta(days=np.random.randint(0, 365))
dis_date = adm_date + timedelta(days=np.random.randint(3, 30))
ward = np.random.choice(wards)
# Culture (50% have cultures)
if np.random.rand() > 0.5:
cult_date = adm_date + timedelta(days=np.random.randint(1, 5))
pathogen = np.random.choice(pathogens)
susc = {ab: np.random.choice(['S', 'R', 'I']) for ab in antibiotics[:3]} # Simplified
susc_str = ';'.join([f"{k}:{v}" for k,v in susc.items()])
else:
cult_date, pathogen, susc_str = pd.NaT, None, None
# Prescription (80% get abx)
if np.random.rand() > 0.2:
drug = np.random.choice(antibiotics)
start_dt = adm_date + timedelta(days=np.random.randint(0, 3))
end_dt = min(dis_date, start_dt + timedelta(days=np.random.randint(2, 14)))
dot = (end_dt - start_dt).days
else:
drug, start_dt, end_dt, dot = None, pd.NaT, pd.NaT, 0
data.append({
'patient_id': f'PT{i+1}',
'admission_date': adm_date,
'discharge_date': dis_date,
'ward': ward,
'culture_date': cult_date,
'pathogen': pathogen,
'susceptibility': susc_str,
'drug_prescribed': drug,
'drug_start': start_dt,
'drug_end': end_dt,
'dot': dot,
'ddd': ddd_dict.get(drug, 1.0)
})
df = pd.DataFrame(data)
df['patient_days'] = (df['discharge_date'] - df['admission_date']).dt.days
return df
@st.cache_data
def calculate_metrics(df):
"""Precompute key AMS metrics."""
# DOT/DDD
dot_df = df[df['dot'] > 0].groupby(['drug_prescribed', pd.Grouper(key='admission_date', freq='M')]).agg({
'dot': 'sum', 'patient_days': 'sum', 'ddd': lambda x: (x * df.loc[x.index, 'dot']).sum() / x.mean() if len(x)>0 else 0
}).reset_index()
dot_df['DOT_1000pd'] = (dot_df['dot'] / dot_df['patient_days']) * 1000
dot_df['DDD_1000pd'] = dot_df['ddd'] / dot_df['patient_days'] * 1000
# Bug-Drug Mismatches: Parse susceptibility and check if prescribed drug is R for pathogen
mismatch_df = df.dropna(subset=['pathogen', 'drug_prescribed', 'susceptibility']).copy()
def is_mismatch(row):
if pd.isna(row['susceptibility']): return False
susc = dict(pair.split(':') for pair in row['susceptibility'].split(';'))
return susc.get(row['drug_prescribed'], 'I') == 'R'
mismatch_df['mismatch'] = mismatch_df.apply(is_mismatch, axis=1)
# De-escalation Windows: Time from culture to narrow-spectrum switch (simplified: any switch after culture)
de_escal_df = df.dropna(subset=['culture_date', 'drug_start']).copy()
de_escal_df['de_escal_days'] = np.where(
de_escal_df['drug_end'] > de_escal_df['culture_date'],
(de_escal_df['drug_end'] - de_escal_df['culture_date']).dt.days,
np.nan
)
return dot_df, mismatch_df, de_escal_df
def dot_ddd_dashboard(df_filtered, dot_df):
"""DOT/DDD Tab."""
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown('<div class="metric-card">Total DOT<br><b style="color:#1f77b4;font-size:2rem;">{:.0f}</b></div>'.format(df_filtered['dot'].sum()), unsafe_allow_html=True)
with col2:
avg_dot = df_filtered['DOT_1000pd'].mean() if 'DOT_1000pd' in dot_df.columns else 0
st.markdown('<div class="metric-card">Avg DOT/1000 PD<br><b style="color:#1f77b4;font-size:2rem;">{:.1f}</b></div>'.format(avg_dot), unsafe_allow_html=True)
with col3:
avg_ddd = dot_df['DDD_1000pd'].mean()
st.markdown('<div class="metric-card">Avg DDD/1000 PD<br><b style="color:#ff7f0e;font-size:2rem;">{:.1f}</b></div>'.format(avg_ddd), unsafe_allow_html=True)
with col4:
top_drug = dot_df.loc[dot_df['DOT_1000pd'].idxmax(), 'drug_prescribed'] if not dot_df.empty else 'N/A'
st.markdown(f'<div class="metric-card">Top Drug<br><b style="color:#2ca02c;font-size:2rem;">{top_drug}</b></div>', unsafe_allow_html=True)
tab1, tab2 = st.tabs(["Trends", "By Ward/Drug"])
with tab1:
fig = px.line(dot_df, x='admission_date', y=['DOT_1000pd', 'DDD_1000pd'], title="DOT/DDD Trends Over Time")
st.plotly_chart(fig, use_container_width=True)
with tab2:
fig_ward = px.bar(dot_df.groupby('ward').agg({'DOT_1000pd':'mean'}).reset_index(), x='ward', y='DOT_1000pd')
st.plotly_chart(fig_ward, use_container_width=True)
fig_drug = px.bar(dot_df.groupby('drug_prescribed')['DOT_1000pd'].mean().sort_values(ascending=False).reset_index(), x='drug_prescribed', y='DOT_1000pd')
fig_drug.update_layout(xaxis_tickangle=45)
st.plotly_chart(fig_drug, use_container_width=True)
def mismatch_dashboard(mismatch_df):
"""Bug-Drug Mismatch Tab."""
mismatch_rate = mismatch_df['mismatch'].mean() * 100
col1, col2 = st.columns(2)
with col1:
st.markdown(f'<div class="alert-card">Mismatch Rate<br><b style="color:#d62728;font-size:3rem;">{mismatch_rate:.1f}%</b></div>', unsafe_allow_html=True)
with col2:
top_mismatch = mismatch_df[mismatch_df['mismatch']]['drug_prescribed'].value_counts().index[0] if mismatch_df['mismatch'].any() else 'None'
st.markdown(f'<div class="alert-card">Top Mismatch Drug<br><b style="color:#d62728;font-size:2rem;">{top_mismatch}</b></div>', unsafe_allow_html=True)
fig = px.histogram(mismatch_df, x='pathogen', color='mismatch', title="Mismatches by Pathogen")
st.plotly_chart(fig, use_container_width=True)
# Heatmap: Drug vs Pathogen mismatch rate
pivot = mismatch_df.pivot_table(index='drug_prescribed', columns='pathogen', values='mismatch', aggfunc='mean').fillna(0) * 100
fig_heat = px.imshow(pivot, title="Mismatch Heatmap (%)", color_continuous_scale='Reds')
st.plotly_chart(fig_heat, use_container_width=True)
def deescal_dashboard(de_escal_df):
"""De-escalation Windows Tab."""
valid_de = de_escal_df.dropna(subset=['de_escal_days'])
if not valid_de.empty:
median_window = valid_de['de_escal_days'].median()
col1, col2 = st.columns(2)
with col1:
st.markdown(f'<div class="metric-card">Median De-escal Window<br><b style="color:#2ca02c;font-size:3rem;">{median_window:.0f} days</b></div>', unsafe_allow_html=True)
with col2:
timely_rate = (valid_de['de_escal_days'] <= 3).mean() * 100 # <72h ideal
st.markdown(f'<div class="metric-card">Timely De-escal (≤3d)<br><b style="color:#2ca02c;font-size:3rem;">{timely_rate:.1f}%</b></div>', unsafe_allow_html=True)
fig = px.box(valid_de, x='ward', y='de_escal_days', title="De-escalation Windows by Ward")
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("No de-escalation data available.")
def feedback_tab(df_filtered, dot_df, mismatch_df, de_escal_df):
"""Feedback Tab: Actionable Insights."""
st.header("🔔 Stewardship Feedback & Alerts")
# High DOT alert
high_dot_drugs = dot_df[dot_df['DOT_1000pd'] > dot_df['DOT_1000pd'].quantile(0.8)]['drug_prescribed'].unique()
if len(high_dot_drugs) > 0:
st.error(f"🚨 **High DOT Alert**: Review {', '.join(high_dot_drugs[:3])} (>80th percentile)")
# Mismatch alert
if mismatch_df['mismatch'].mean() > 0.1:
st.warning(f"⚠️ **Mismatch Alert**: {mismatch_df['mismatch'].mean()*100:.1f}% bug-drug mismatches. Audit recent cases.")
# Slow de-escal
valid_de = de_escal_df.dropna(subset=['de_escal_days'])
if not valid_de.empty and valid_de['de_escal_days'].median() > 3:
st.warning("⏳ **De-escalation Delay**: Median window >72h. Target faster narrowing post-culture.")
# Downloadable report
buf = io.StringIO()
buf.write("AMS Summary Report\n")
buf.write(f"Date Range: {st.session_state.get('start_date', 'N/A')} to {st.session_state.get('end_date', 'N/A')}\n")
buf.write(f"Total Patients: {len(df_filtered)}\n")
buf.write(f"Total DOT: {df_filtered['dot'].sum():.0f}\n")
buf.write(f"Avg DOT/1000 PD: {dot_df['DOT_1000pd'].mean():.1f}\n")
buf.write(f"Mismatch Rate: {mismatch_df['mismatch'].mean()*100:.1f}%\n")
if not valid_de.empty:
buf.write(f"Median De-escal: {valid_de['de_escal_days'].median():.0f} days\n")
csv = buf.getvalue()
st.download_button("📥 Download Feedback Report", csv, "ams_feedback.txt", "text/plain")
# Main App
st.title("🏥 Hospital Antimicrobial Stewardship (AMS) Analytics Cockpit")
st.markdown("Track DOT/DDD, bug-drug mismatches, de-escalation, and get real-time feedback.")
@st.cache_data
def get_data():
raw_df = load_synthetic_data()
dot_df, mismatch_df, de_escal_df = calculate_metrics(raw_df)
return raw_df, dot_df, mismatch_df, de_escal_df
raw_df, dot_df_full, mismatch_df_full, de_escal_df_full = get_data()
# Filters (Sidebar)
st.sidebar.header("🔍 Filters")
wards = st.sidebar.multiselect("Ward", options=sorted(raw_df['ward'].unique()), default=sorted(raw_df['ward'].unique()))
drugs = st.sidebar.multiselect("Drug", options=sorted(raw_df['drug_prescribed'].dropna().unique()), default=[])
col1, col2 = st.sidebar.columns(2)
start_date = col1.date_input("Start Date", raw_df['admission_date'].min().date())
end_date = col2.date_input("End Date", raw_df['admission_date'].max().date())
st.session_state['start_date'] = start_date
st.session_state['end_date'] = end_date
# Apply filters
df_filtered = raw_df[
(raw_df['admission_date'] >= pd.to_datetime(start_date)) &
(raw_df['admission_date'] <= pd.to_datetime(end_date)) &
(raw_df['ward'].isin(wards)) &
(raw_df['drug_prescribed'].isin(drugs) if drugs else True)
].copy()
dot_df = calculate_metrics(df_filtered)[0]
mismatch_df = calculate_metrics(df_filtered)[1]
de_escal_df = calculate_metrics(df_filtered)[2]
# Tabs
tab1, tab2, tab3, tab4 = st.tabs(["📊 DOT/DDD", "🐛 Bug-Drug Mismatches", "⏳ De-escalation Windows", "🔔 Feedback"])
with tab1:
dot_ddd_dashboard(df_filtered, dot_df)
with tab2:
mismatch_dashboard(mismatch_df)
with tab3:
deescal_dashboard(de_escal_df)
with tab4:
feedback_tab(df_filtered, dot_df, mismatch_df, de_escal_df)
# Footer
st.markdown("---")
st.markdown("**Built by Sherlock (Trailblazer Labs)** | *Synthetic data for demo. Replace `load_synthetic_data()` with real EMR data (e.g., Epic/Cerner extracts).*")