import streamlit as st import plotly.graph_objects as go import pandas as pd # ── Page config ─────────────────────────────────────────────────────────────── st.set_page_config( page_title="T2.3 · Grid Outage Forecaster", page_icon="⚡", layout="wide", ) # ── Custom CSS ───────────────────────────────────────────────────────────────── st.markdown(""" """, unsafe_allow_html=True) # ── Embedded Data ───────────────────────────────────────────────────────────── FORECAST = [ {"hour_offset":0,"timestamp":"2024-06-29 00:00","hour":0,"p_outage":0.2708,"p_outage_low":0.1908,"p_outage_high":0.3508,"expected_duration_min":89.8,"risk_level":"HIGH"}, {"hour_offset":1,"timestamp":"2024-06-29 01:00","hour":1,"p_outage":0.2554,"p_outage_low":0.1754,"p_outage_high":0.3354,"expected_duration_min":83.2,"risk_level":"HIGH"}, {"hour_offset":2,"timestamp":"2024-06-29 02:00","hour":2,"p_outage":0.2169,"p_outage_low":0.1369,"p_outage_high":0.2969,"expected_duration_min":85.0,"risk_level":"MEDIUM"}, {"hour_offset":3,"timestamp":"2024-06-29 03:00","hour":3,"p_outage":0.2554,"p_outage_low":0.1754,"p_outage_high":0.3354,"expected_duration_min":85.0,"risk_level":"HIGH"}, {"hour_offset":4,"timestamp":"2024-06-29 04:00","hour":4,"p_outage":0.2602,"p_outage_low":0.1802,"p_outage_high":0.3402,"expected_duration_min":78.8,"risk_level":"HIGH"}, {"hour_offset":5,"timestamp":"2024-06-29 05:00","hour":5,"p_outage":0.2503,"p_outage_low":0.1703,"p_outage_high":0.3303,"expected_duration_min":85.0,"risk_level":"HIGH"}, {"hour_offset":6,"timestamp":"2024-06-29 06:00","hour":6,"p_outage":0.24, "p_outage_low":0.16, "p_outage_high":0.32, "expected_duration_min":83.2,"risk_level":"MEDIUM"}, {"hour_offset":7,"timestamp":"2024-06-29 07:00","hour":7,"p_outage":0.2208,"p_outage_low":0.1408,"p_outage_high":0.3008,"expected_duration_min":78.5,"risk_level":"MEDIUM"}, {"hour_offset":8,"timestamp":"2024-06-29 08:00","hour":8,"p_outage":0.2208,"p_outage_low":0.1408,"p_outage_high":0.3008,"expected_duration_min":78.5,"risk_level":"MEDIUM"}, {"hour_offset":9,"timestamp":"2024-06-29 09:00","hour":9,"p_outage":0.198, "p_outage_low":0.118, "p_outage_high":0.278, "expected_duration_min":86.0,"risk_level":"MEDIUM"}, {"hour_offset":10,"timestamp":"2024-06-29 10:00","hour":10,"p_outage":0.24, "p_outage_low":0.16, "p_outage_high":0.32, "expected_duration_min":71.3,"risk_level":"MEDIUM"}, {"hour_offset":11,"timestamp":"2024-06-29 11:00","hour":11,"p_outage":0.2531,"p_outage_low":0.1731,"p_outage_high":0.3331,"expected_duration_min":73.1,"risk_level":"HIGH"}, {"hour_offset":12,"timestamp":"2024-06-29 12:00","hour":12,"p_outage":0.2457,"p_outage_low":0.1657,"p_outage_high":0.3257,"expected_duration_min":76.9,"risk_level":"MEDIUM"}, {"hour_offset":13,"timestamp":"2024-06-29 13:00","hour":13,"p_outage":0.263, "p_outage_low":0.183, "p_outage_high":0.343, "expected_duration_min":68.8,"risk_level":"HIGH"}, {"hour_offset":14,"timestamp":"2024-06-29 14:00","hour":14,"p_outage":0.2582,"p_outage_low":0.1782,"p_outage_high":0.3382,"expected_duration_min":72.5,"risk_level":"HIGH"}, {"hour_offset":15,"timestamp":"2024-06-29 15:00","hour":15,"p_outage":0.2194,"p_outage_low":0.1394,"p_outage_high":0.2994,"expected_duration_min":76.9,"risk_level":"MEDIUM"}, {"hour_offset":16,"timestamp":"2024-06-29 16:00","hour":16,"p_outage":0.2688,"p_outage_low":0.1888,"p_outage_high":0.3488,"expected_duration_min":83.4,"risk_level":"HIGH"}, {"hour_offset":17,"timestamp":"2024-06-29 17:00","hour":17,"p_outage":0.309, "p_outage_low":0.229, "p_outage_high":0.389, "expected_duration_min":84.6,"risk_level":"HIGH"}, {"hour_offset":18,"timestamp":"2024-06-29 18:00","hour":18,"p_outage":0.3353,"p_outage_low":0.2553,"p_outage_high":0.4153,"expected_duration_min":84.6,"risk_level":"HIGH"}, {"hour_offset":19,"timestamp":"2024-06-29 19:00","hour":19,"p_outage":0.3408,"p_outage_low":0.2608,"p_outage_high":0.4208,"expected_duration_min":76.1,"risk_level":"HIGH"}, {"hour_offset":20,"timestamp":"2024-06-29 20:00","hour":20,"p_outage":0.3353,"p_outage_low":0.2553,"p_outage_high":0.4153,"expected_duration_min":99.4,"risk_level":"HIGH"}, {"hour_offset":21,"timestamp":"2024-06-29 21:00","hour":21,"p_outage":0.3466,"p_outage_low":0.2666,"p_outage_high":0.4266,"expected_duration_min":100.6,"risk_level":"HIGH"}, {"hour_offset":22,"timestamp":"2024-06-29 22:00","hour":22,"p_outage":0.2834,"p_outage_low":0.2034,"p_outage_high":0.3634,"expected_duration_min":102.5,"risk_level":"HIGH"}, {"hour_offset":23,"timestamp":"2024-06-29 23:00","hour":23,"p_outage":0.2596,"p_outage_low":0.1796,"p_outage_high":0.3396,"expected_duration_min":106.9,"risk_level":"HIGH"}, ] SMS = [ "UMURIRO FORECAST 24H: Risk=HIGH at 0h,1h,3h. Shed: Standing+TV. Est.save: 12,418RWF. Stay alert!", "PLAN: Turn OFF Standing+TV during risk hrs (0h,1h,3h). Keep dryer+clippers+lights ON. Generator ready?", "If no signal by 13h, use YESTERDAY plan. Risk valid 6h. Call 0788-GRID for live update. Good business!", ] # ── Appliance plan generators ───────────────────────────────────────────────── def salon_appliances(hour, risk): open_ = 7 <= hour <= 20 peak = 9 <= hour <= 17 scale = 1.0 if peak else (0.75 if open_ else 0.0) if not open_: return [ {"name":"Hair Dryer (2×)", "category":"critical","state":"OFF","watts":2400,"revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"Electric Clippers (3×)","category":"critical","state":"OFF","watts":120, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"LED Lights", "category":"critical","state":"ON", "watts":20, "revenue_rwf":0}, {"name":"Standing Fan", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"TV / Display", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"Music System", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"Neon Sign", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, ] shed_lux = risk in ("HIGH","MEDIUM") shed_com = risk == "HIGH" return [ {"name":"Hair Dryer (2×)", "category":"critical","state":"ON", "watts":2400,"revenue_rwf":round(2133*scale)}, {"name":"Electric Clippers (3×)","category":"critical","state":"ON", "watts":120, "revenue_rwf":round(1422*scale)}, {"name":"LED Lights", "category":"critical","state":"ON", "watts":80, "revenue_rwf":round(711*scale)}, {"name":"Standing Fan", "category":"comfort","state":"OFF" if shed_com else "ON","watts":0 if shed_com else 75, "revenue_rwf":0 if shed_com else round(285*scale), **({"shed_reason":"HIGH risk — comfort shed"} if shed_com else {})}, {"name":"TV / Display", "category":"comfort","state":"OFF" if shed_com else "ON","watts":0 if shed_com else 150,"revenue_rwf":0 if shed_com else round(142*scale), **({"shed_reason":"HIGH risk — comfort shed"} if shed_com else {})}, {"name":"Music System", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 80, "revenue_rwf":0, **({"shed_reason":"Risk ≥ MEDIUM — luxury shed"} if shed_lux else {})}, {"name":"Neon Sign", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 40, "revenue_rwf":0, **({"shed_reason":"Risk ≥ MEDIUM — luxury shed"} if shed_lux else {})}, ] def cold_appliances(hour, risk): open_ = 6 <= hour <= 20 peak = 8 <= hour <= 18 scale = 1.0 if peak else (0.6 if open_ else 0.0) fridge_rev = round(1850*scale) if open_ else 0 pump_rev = round(1100*scale) if open_ else 0 light_rev = round(740*scale) if open_ else 0 fan_rev = round(296*scale) if open_ else 0 tv_rev = round(148*scale) if open_ else 0 shed_com = risk == "HIGH" shed_fan = shed_com or not open_ shed_tv = shed_com or not open_ return [ {"name":"Commercial Refrigerator","category":"critical","state":"ON", "watts":350,"revenue_rwf":fridge_rev or 200,**({"shed_reason":"After-hours — standby mode"} if not open_ else {})}, {"name":"Water Pump", "category":"critical","state":"ON" if open_ else "OFF","watts":750 if open_ else 0,"revenue_rwf":pump_rev, **({"shed_reason":"After-hours — pump off"} if not open_ else {})}, {"name":"LED Lights", "category":"critical","state":"ON" if open_ else "OFF","watts":80 if open_ else 0,"revenue_rwf":light_rev,**({"shed_reason":"After-hours — lights off"} if not open_ else {})}, {"name":"Standing Fan", "category":"comfort", "state":"OFF" if shed_fan else "ON","watts":0 if shed_fan else 75, "revenue_rwf":0 if shed_fan else fan_rev,**({"shed_reason":"HIGH risk — comfort shed" if shed_com else "After-hours"} if shed_fan else {})}, {"name":"TV / Display", "category":"comfort", "state":"OFF" if shed_tv else "ON","watts":0 if shed_tv else 150,"revenue_rwf":0 if shed_tv else tv_rev, **({"shed_reason":"HIGH risk — comfort shed" if shed_com else "After-hours"} if shed_tv else {})}, {"name":"Backup Battery Charger","category":"luxury","state":"ON" if (risk=="LOW" and open_) else "OFF","watts":200 if (risk=="LOW" and open_) else 0,"revenue_rwf":0,**({"shed_reason":"Risk ≥ MEDIUM — luxury shed"} if not (risk=="LOW" and open_) else {})}, ] def tailor_appliances(hour, risk): open_ = 8 <= hour <= 18 peak = 9 <= hour <= 16 scale = 1.0 if peak else (0.6 if open_ else 0.0) if not open_: return [ {"name":"Sewing Machine (2×)","category":"critical","state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"Overlocker", "category":"critical","state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"LED Lights", "category":"critical","state":"ON", "watts":20, "revenue_rwf":0}, {"name":"Iron Press", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"Standing Fan", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"Music System", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, {"name":"TV / Display", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"}, ] shed_lux = risk in ("HIGH","MEDIUM") shed_com = risk == "HIGH" shed_iron= risk == "HIGH" return [ {"name":"Sewing Machine (2×)","category":"critical","state":"ON","watts":180,"revenue_rwf":round(590*scale)}, {"name":"Overlocker", "category":"critical","state":"ON","watts":100,"revenue_rwf":round(310*scale)}, {"name":"LED Lights", "category":"critical","state":"ON","watts":80, "revenue_rwf":round(180*scale)}, {"name":"Iron Press", "category":"comfort","state":"OFF" if shed_iron else "ON","watts":0 if shed_iron else 1000,"revenue_rwf":0 if shed_iron else round(260*scale),**({"shed_reason":"HIGH risk — heavy load shed"} if shed_iron else {})}, {"name":"Standing Fan", "category":"comfort","state":"OFF" if shed_com else "ON","watts":0 if shed_com else 75, "revenue_rwf":0 if shed_com else round(120*scale),**({"shed_reason":"HIGH risk — comfort shed"} if shed_com else {})}, {"name":"Music System", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 80, "revenue_rwf":0,**({"shed_reason":"Risk ≥ MEDIUM — luxury shed"} if shed_lux else {})}, {"name":"TV / Display", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 150, "revenue_rwf":0,**({"shed_reason":"Risk ≥ MEDIUM — luxury shed"} if shed_lux else {})}, ] PLANS = { "salon": { "label": "💇 Beauty Salon", "summary": {"total_revenue_plan_rwf":93850,"total_revenue_naive_rwf":101790,"net_benefit_rwf":12418,"hours_with_shed":24}, "fn": salon_appliances, }, "cold_room": { "label": "🧊 Cold Room", "summary": {"total_revenue_plan_rwf":118000,"total_revenue_naive_rwf":125000,"net_benefit_rwf":18000,"hours_with_shed":16}, "fn": cold_appliances, }, "tailor": { "label": "🧵 Tailor Shop", "summary": {"total_revenue_plan_rwf":42000,"total_revenue_naive_rwf":48000,"net_benefit_rwf":3600,"hours_with_shed":14}, "fn": tailor_appliances, }, } RISK_COLOR = {"HIGH": "#ef4444", "MEDIUM": "#f97316", "LOW": "#22c55e"} # ── Sidebar ─────────────────────────────────────────────────────────────────── with st.sidebar: st.markdown("## ⚡ Grid Outage Forecaster") st.markdown("T2.3 · AIMS KTT Hackathon 2026 · Kigali, Rwanda", unsafe_allow_html=True) st.divider() st.markdown("### Model Metrics") st.metric("Brier Score", "0.176") st.metric("MAE (min)", "61.2") st.metric("Avg Lead Time", "2.79h") st.divider() st.markdown("### Business") biz_key = st.radio( "Select business", options=list(PLANS.keys()), format_func=lambda k: PLANS[k]["label"], label_visibility="collapsed", ) st.divider() biz = PLANS[biz_key] s = biz["summary"] st.markdown("### Plan Summary") st.metric("Net Benefit (RWF)", f"{s['net_benefit_rwf']:,}") st.metric("Expected Rev (RWF)", f"{s['total_revenue_plan_rwf']:,}") high_h = sum(1 for f in FORECAST if f["risk_level"] == "HIGH") st.metric("HIGH Risk Hours", high_h) st.metric("Hours with Shed", s["hours_with_shed"]) # ── Main tabs ───────────────────────────────────────────────────────────────── tab_forecast, tab_plan, tab_sms, tab_about = st.tabs( ["📈 Forecast", "🔌 Appliance Plan", "📱 SMS Digest", "ℹ️ About"] ) # ══ FORECAST TAB ══════════════════════════════════════════════════════════════ with tab_forecast: st.markdown("### 24-Hour Outage Probability Forecast") hours = [f["hour"] for f in FORECAST] p_out = [f["p_outage"] for f in FORECAST] p_low = [f["p_outage_low"] for f in FORECAST] p_high = [f["p_outage_high"] for f in FORECAST] risk_levels = [f["risk_level"] for f in FORECAST] bar_colors = [RISK_COLOR[r] for r in risk_levels] fig = go.Figure() # Risk background zones (coloured bar under chart) for f in FORECAST: col = {"HIGH":"rgba(239,68,68,.10)","MEDIUM":"rgba(249,115,22,.07)","LOW":"rgba(34,197,94,.04)"}[f["risk_level"]] fig.add_vrect(x0=f["hour"]-.5, x1=f["hour"]+.5, fillcolor=col, line_width=0, layer="below") # Uncertainty band fig.add_trace(go.Scatter( x=hours + hours[::-1], y=p_high + p_low[::-1], fill="toself", fillcolor="rgba(99,102,241,.18)", line=dict(color="rgba(0,0,0,0)"), hoverinfo="skip", name="Uncertainty band", )) # Main line fig.add_trace(go.Scatter( x=hours, y=p_out, mode="lines+markers", line=dict(color="#6366f1", width=2.5), marker=dict(color=bar_colors, size=8, line=dict(color="#0f1117", width=1)), name="P(outage)", hovertemplate="Hour %{x}:00
P(outage)=%{y:.1%}", )) # HIGH threshold line fig.add_hline(y=0.25, line=dict(color="#ef4444", dash="dash", width=1), annotation_text="HIGH threshold", annotation_position="top left", annotation_font_color="#ef4444") fig.update_layout( paper_bgcolor="#1a1d27", plot_bgcolor="#1a1d27", font=dict(color="#e8eaf6", size=12), xaxis=dict(title="Hour of day", gridcolor="#2e3350", tickvals=list(range(0,24,2))), yaxis=dict(title="P(outage)", gridcolor="#2e3350", tickformat=".0%", range=[0, 0.55]), legend=dict(orientation="h", y=1.08, bgcolor="rgba(0,0,0,0)"), margin=dict(l=10, r=10, t=10, b=10), height=320, ) st.plotly_chart(fig, use_container_width=True) # ── Hour grid ───────────────────────────────────────────────────────────── st.markdown("### Hourly Risk — click a cell to drill into plan") cols = st.columns(12) for i, f in enumerate(FORECAST): col_idx = i % 12 with cols[col_idx]: risk = f["risk_level"] color = RISK_COLOR[risk] pct = f"{f['p_outage']*100:.0f}%" st.markdown(f"""
{f["hour"]}h
{pct}
{risk}
""", unsafe_allow_html=True) cols2 = st.columns(12) for i, f in enumerate(FORECAST): with cols2[i % 12]: pass # second row of 12 hours already handled above # Second row (hours 12–23) st.markdown("") # ══ PLAN TAB ══════════════════════════════════════════════════════════════════ with tab_plan: st.markdown("### 🔌 Appliance Plan") hour_idx = st.slider( "Select hour", min_value=0, max_value=23, value=0, format="%d:00", ) fc = FORECAST[hour_idx] appliances = biz["fn"](hour_idx, fc["risk_level"]) risk = fc["risk_level"] # Hour info header risk_color = RISK_COLOR[risk] st.markdown(f"""
Hour {hour_idx}  ·  {fc['timestamp'].split()[1]}   {risk}   P(outage) = {fc['p_outage']*100:.1f}%   Exp. duration = {fc['expected_duration_min']:.0f} min
""", unsafe_allow_html=True) # Appliance cards in 2 columns left_col, right_col = st.columns(2) for i, ap in enumerate(appliances): target = left_col if i % 2 == 0 else right_col is_off = ap["state"] == "OFF" opacity = "opacity:.65;" if is_off else "" shed = f"
⚠ {ap['shed_reason']}
" if "shed_reason" in ap else "" rev_html = f"
{ap['revenue_rwf']:,} RWF/h
" if ap["state"] == "ON" and ap["revenue_rwf"] > 0 else "
" with target: st.markdown(f"""
{ap['name']}
{ap['category']} {ap['state']}
{shed}
{ap['watts']}W
{rev_html}
""", unsafe_allow_html=True) st.markdown("""
Shedding Logic: Luxury → Comfort → Critical (never shed during peak unless P > 0.50). Within category: lowest revenue shed first. Critical always ON during business peak hours.
""", unsafe_allow_html=True) # ══ SMS TAB ═══════════════════════════════════════════════════════════════════ with tab_sms: st.markdown("### 📱 Morning Digest — Feature Phone SMS") st.markdown("Sent at 06:30 CAT. Max 3 messages × 160 chars. Works on any GSM phone. No internet required. Language: Kinyarwanda/English mix for maximum reach.", unsafe_allow_html=True) st.markdown("") for i, msg in enumerate(SMS): st.markdown(f"""
SMS {i+1}/3 {len(msg)}/160 chars
{msg}
""", unsafe_allow_html=True) st.markdown("""
🔕 Offline Fallback Protocol
If no internet refresh by 13:00: Device shows last cached plan with a red ⚠️ staleness banner. Risk budget: plan valid for 6 hours from generation time. After 6h, all HIGH-risk flags remain but MEDIUM degrades to LOW (overly cautious). Maximum acceptable staleness: 8 hours. Owner sees: "PLAN STALE — use generator, call 0788-GRID."
🔊 Illiteracy Adaptation — Voice + LED Relay
Design choice: Colored LED relay board (3 LEDs per appliance slot).
🟢 GREEN = ON safe  ·  🟡 YELLOW = shed if load high  ·  🔴 RED = OFF now.
Board connects via GPIO to a ≈USD 8 ESP32 running cached plan. No reading required. Physical override switch lets owner override any LED. $8 hardware cost, zero ongoing data cost.
""", unsafe_allow_html=True) # ══ ABOUT TAB ═════════════════════════════════════════════════════════════════ with tab_about: st.markdown("### Technical Notes") col1, col2 = st.columns(2) with col1: st.markdown("""
Model
LightGBM classifier for P(outage) + regressor for E[duration | outage].
Features: lagged load (1h, 2h, 24h, 48h), rolling stats, weather (temp, humidity, rain, wind), temporal (hour, DOW, month, peak flags, rainy season). Training: 150-day window.
""", unsafe_allow_html=True) st.markdown("""
Hardest Trade-off
Chose LightGBM over Prophet: faster retrain, handles irregular time steps, natively supports tabular weather features. Trade-off: less interpretable seasonality decomposition. Compensated with explicit hour/DOW/month features and SHAP values available in eval notebook.
""", unsafe_allow_html=True) with col2: st.markdown("""
Performance
Brier score: 0.1756 (naïve base rate = ~0.212)
Duration MAE: 61.2 min
Avg lead time on true outages: 2.79h
Inference latency: <300ms CPU
Retraining time: <10 min
""", unsafe_allow_html=True) st.markdown("""
Constraints Met
✅ CPU-only  ·  ✅ <10 min retrain  ·  ✅ <300ms serve
✅ Feature phone SMS digest  ·  ✅ Offline fallback protocol
✅ Illiteracy adaptation  ·  ✅ 3 business archetypes
✅ Critical-before-luxury rule
""", unsafe_allow_html=True) st.markdown("""
T2.3 · Grid Outage Forecaster + Appliance Prioritizer · AIMS KTT Hackathon 2026 · CPU-only
""", unsafe_allow_html=True)