Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +472 -205
src/streamlit_app.py
CHANGED
|
@@ -4,6 +4,7 @@ import numpy as np
|
|
| 4 |
import json
|
| 5 |
import joblib
|
| 6 |
from pathlib import Path
|
|
|
|
| 7 |
from dateutil.relativedelta import relativedelta
|
| 8 |
import plotly.express as px
|
| 9 |
import plotly.graph_objects as go
|
|
@@ -27,10 +28,12 @@ st.markdown(
|
|
| 27 |
"""
|
| 28 |
<style>
|
| 29 |
.block-container {padding-top:2rem;padding-bottom:2rem;}
|
|
|
|
| 30 |
.card {background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);
|
| 31 |
border-radius:16px;padding:14px;margin-bottom:10px;}
|
| 32 |
-
.small-note {opacity:0.
|
| 33 |
-
.legend-dot {display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:
|
|
|
|
| 34 |
</style>
|
| 35 |
""",
|
| 36 |
unsafe_allow_html=True,
|
|
@@ -40,142 +43,314 @@ st.markdown(
|
|
| 40 |
# LOADERS
|
| 41 |
# -------------------------------------------------------
|
| 42 |
@st.cache_data
|
| 43 |
-
def load_csv(name
|
| 44 |
return pd.read_csv(p(name))
|
| 45 |
|
| 46 |
@st.cache_data
|
| 47 |
-
def load_geo(name):
|
| 48 |
with open(p(name), "r", encoding="utf-8") as f:
|
| 49 |
return json.load(f)
|
| 50 |
|
| 51 |
@st.cache_resource
|
| 52 |
-
def load_model(name
|
| 53 |
return joblib.load(p(name))
|
| 54 |
|
| 55 |
@st.cache_data
|
| 56 |
-
def load_json(name):
|
| 57 |
with open(p(name), "r", encoding="utf-8") as f:
|
| 58 |
return json.load(f)
|
| 59 |
|
| 60 |
# -------------------------------------------------------
|
| 61 |
-
#
|
| 62 |
# -------------------------------------------------------
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
national = load_csv("national_trend.csv")
|
| 66 |
-
top10 = load_csv("top10_by_month.csv")
|
| 67 |
-
baseline = load_csv("baseline_latest_features.csv")
|
| 68 |
-
feature_importance = load_csv("feature_importance.csv")
|
| 69 |
-
geojson = load_geo("kenya_counties.geojson")
|
| 70 |
-
model = load_model("model.joblib")
|
| 71 |
-
FEATURES = load_json("features.json")
|
| 72 |
-
|
| 73 |
-
# -------------------------------------------------------
|
| 74 |
-
# STANDARDIZE
|
| 75 |
-
# -------------------------------------------------------
|
| 76 |
-
def normalize(x):
|
| 77 |
-
if pd.isna(x):
|
| 78 |
return ""
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
if
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
# -------------------------------------------------------
|
| 96 |
-
#
|
| 97 |
# -------------------------------------------------------
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
# -------------------------------------------------------
|
| 106 |
# RISK BANDS + COLORS
|
| 107 |
# -------------------------------------------------------
|
| 108 |
RISK_COLORS = {
|
| 109 |
-
"Secure":
|
| 110 |
-
"Watch":
|
| 111 |
-
"High":
|
| 112 |
"Extreme": "#dc2626",
|
|
|
|
| 113 |
}
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
return "Secure"
|
| 118 |
-
if p < min(thr + 0.15, 1):
|
| 119 |
return "Watch"
|
| 120 |
-
if p < min(thr + 0.35, 1):
|
| 121 |
return "High"
|
| 122 |
return "Extreme"
|
| 123 |
|
| 124 |
# -------------------------------------------------------
|
| 125 |
-
# TABLE STYLING
|
| 126 |
# -------------------------------------------------------
|
| 127 |
def _hex_to_rgba(hex_color: str, alpha: float = 0.18) -> str:
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
r = int(hex_color[0:2], 16)
|
| 131 |
-
g = int(hex_color[2:4], 16)
|
| 132 |
-
b = int(hex_color[4:6], 16)
|
| 133 |
return f"rgba({r},{g},{b},{alpha})"
|
| 134 |
|
| 135 |
def style_risk_table(df: pd.DataFrame) -> "pd.io.formats.style.Styler":
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
- 'risk_proba' shows a bar
|
| 140 |
-
- numeric formatting
|
| 141 |
-
"""
|
| 142 |
-
show = df.copy()
|
| 143 |
-
|
| 144 |
-
if "risk_proba" in show.columns:
|
| 145 |
-
show["risk_proba"] = pd.to_numeric(show["risk_proba"], errors="coerce")
|
| 146 |
|
| 147 |
-
|
| 148 |
-
cols = [c for c in ["county", "risk_proba", "band"] if c in show.columns]
|
| 149 |
if cols:
|
| 150 |
-
|
| 151 |
|
| 152 |
-
sty =
|
| 153 |
|
| 154 |
-
if "risk_proba" in
|
| 155 |
sty = sty.format({"risk_proba": "{:.3f}"})
|
| 156 |
-
sty = sty.bar(subset=["risk_proba"], vmin=0.0, vmax=1.0)
|
| 157 |
|
| 158 |
-
if "band" in
|
| 159 |
-
def
|
| 160 |
-
c = RISK_COLORS.get(str(
|
| 161 |
-
|
| 162 |
-
|
| 163 |
|
| 164 |
-
sty = sty.applymap(color_band_cell, subset=["band"])
|
| 165 |
-
|
| 166 |
-
# Light cosmetics
|
| 167 |
sty = sty.set_properties(**{
|
| 168 |
"border": "1px solid rgba(255,255,255,0.06)",
|
| 169 |
"padding": "8px",
|
| 170 |
"font-size": "0.95rem",
|
|
|
|
| 171 |
}).set_table_styles([
|
| 172 |
{"selector": "th", "props": [("font-weight", "700"), ("text-align", "left")]},
|
| 173 |
-
{"selector": "td", "props": [("text-align", "left")]},
|
| 174 |
-
{"selector": "caption", "props": [("caption-side", "bottom"), ("opacity", "0.75")]},
|
| 175 |
])
|
| 176 |
|
| 177 |
return sty
|
| 178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
# -------------------------------------------------------
|
| 180 |
# SIDEBAR
|
| 181 |
# -------------------------------------------------------
|
|
@@ -185,15 +360,19 @@ threshold = st.sidebar.slider("Risk Threshold", 0.10, 0.90, 0.45, 0.01)
|
|
| 185 |
|
| 186 |
page = st.sidebar.radio(
|
| 187 |
"Navigation",
|
| 188 |
-
["National Situation", "Risk Map", "Scenario
|
| 189 |
)
|
| 190 |
|
| 191 |
st.sidebar.markdown("### Risk Bands")
|
| 192 |
-
for k,
|
| 193 |
st.sidebar.markdown(
|
| 194 |
-
f"<span class='legend-dot' style='background:{
|
| 195 |
unsafe_allow_html=True,
|
| 196 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
# =======================================================
|
| 199 |
# NATIONAL SITUATION
|
|
@@ -202,36 +381,48 @@ if page == "National Situation":
|
|
| 202 |
st.title("National Risk Situation")
|
| 203 |
|
| 204 |
latest_data = hist[hist["month"] == latest_hist_month].copy()
|
| 205 |
-
latest_data["band"] = latest_data["risk_proba"].apply(lambda x:
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
|
| 210 |
col1, col2, col3, col4 = st.columns(4)
|
| 211 |
-
col1.metric("
|
| 212 |
-
col2.metric("National Risk Index", f"{latest_data['risk_proba'].mean():.2f}")
|
| 213 |
-
col3.metric("Counties
|
| 214 |
-
col4.metric("
|
| 215 |
-
|
| 216 |
-
st.markdown("### Forecast Outlook")
|
| 217 |
-
|
| 218 |
-
col5, col6 = st.columns(2)
|
| 219 |
-
col5.metric("Forecast National Risk", f"{forecast_data['risk_proba'].mean():.2f}")
|
| 220 |
-
col6.metric("Forecast Counties At Risk", int((forecast_data["risk_proba"] >= threshold).sum()))
|
| 221 |
|
|
|
|
| 222 |
fig = go.Figure()
|
| 223 |
-
trend = national.sort_values("month")
|
| 224 |
-
fig.add_trace(go.Scatter(x=trend["month"], y=trend["national_avg_risk"], mode="lines", name="
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
st.plotly_chart(fig, use_container_width=True)
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
else:
|
| 234 |
-
st.
|
| 235 |
|
| 236 |
# =======================================================
|
| 237 |
# RISK MAP
|
|
@@ -239,96 +430,151 @@ if page == "National Situation":
|
|
| 239 |
elif page == "Risk Map":
|
| 240 |
st.title("County Risk Map")
|
| 241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
view = st.radio("View", ["Historical", "Forecast"], horizontal=True)
|
| 243 |
|
| 244 |
if view == "Historical":
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
| 247 |
else:
|
| 248 |
df = forecast.copy()
|
| 249 |
display_month = forecast_month
|
| 250 |
|
| 251 |
-
df["
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
|
|
|
| 275 |
|
| 276 |
# =======================================================
|
| 277 |
-
# SCENARIO
|
| 278 |
# =======================================================
|
| 279 |
-
elif page == "Scenario
|
| 280 |
st.title("Scenario Simulation")
|
| 281 |
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
county = st.selectbox("Select County", counties)
|
| 284 |
|
| 285 |
base_row = baseline[baseline["county"] == county].copy()
|
| 286 |
if base_row.empty:
|
|
|
|
| 287 |
st.stop()
|
| 288 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
x_base = base_row.iloc[[0]][FEATURES].copy()
|
| 290 |
x_edit = x_base.copy()
|
| 291 |
|
| 292 |
-
st.markdown("Adjust inputs, then run prediction.")
|
| 293 |
|
| 294 |
-
#
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
|
| 306 |
-
with st.expander("Advanced: Edit
|
| 307 |
-
rename_map = {
|
| 308 |
-
"vim_lag_1": "Vegetation condition (1-month lag)",
|
| 309 |
-
"vim_lag_2": "Vegetation condition (2-month lag)",
|
| 310 |
-
"vim_lag_3": "Vegetation condition (3-month lag)",
|
| 311 |
-
"price_lag_1": "Food price level (lag 1)",
|
| 312 |
-
"maize_price_per_kg": "Maize price per kg",
|
| 313 |
-
"events_lag_1": "Conflict events (1-month lag)",
|
| 314 |
-
"fatalities_lag_1": "Conflict fatalities (1-month lag)",
|
| 315 |
-
"is_ASAL": "ASAL county indicator",
|
| 316 |
-
}
|
| 317 |
for f in FEATURES:
|
| 318 |
-
label =
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
if st.button("Run Prediction", use_container_width=True):
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
|
|
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
# =======================================================
|
| 334 |
# COUNTY PROFILE
|
|
@@ -336,47 +582,68 @@ elif page == "Scenario Simulator":
|
|
| 336 |
elif page == "County Profile":
|
| 337 |
st.title("County Profile")
|
| 338 |
|
| 339 |
-
counties = sorted(hist["county"].unique())
|
| 340 |
county = st.selectbox("Select County", counties)
|
| 341 |
|
| 342 |
-
hist_c = hist[hist["county"] == county].sort_values("month")
|
| 343 |
-
|
|
|
|
|
|
|
| 344 |
|
|
|
|
| 345 |
fig = go.Figure()
|
| 346 |
-
fig.add_trace(
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
|
| 355 |
-
if not forecast_c.empty:
|
| 356 |
-
fig.add_trace(
|
| 357 |
-
go.Scatter(
|
| 358 |
-
x=[forecast_month],
|
| 359 |
-
y=[forecast_c["risk_proba"].iloc[0]],
|
| 360 |
-
mode="markers",
|
| 361 |
-
name="Forecast",
|
| 362 |
-
)
|
| 363 |
-
)
|
| 364 |
fig.add_hline(y=threshold, line_dash="dot")
|
| 365 |
-
fig.update_layout(height=
|
| 366 |
st.plotly_chart(fig, use_container_width=True)
|
| 367 |
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
|
|
|
|
|
|
|
|
|
| 375 |
|
|
|
|
| 376 |
st.subheader("Key Drivers (Plain Language)")
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
# =======================================================
|
| 382 |
# ABOUT
|
|
@@ -387,11 +654,11 @@ elif page == "About":
|
|
| 387 |
f"""
|
| 388 |
This dashboard forecasts IPC Phase 3+ (Crisis) risk at county level.
|
| 389 |
|
| 390 |
-
-
|
| 391 |
-
-
|
| 392 |
-
- Scenario
|
| 393 |
-
- County Profile
|
| 394 |
|
| 395 |
-
|
| 396 |
"""
|
| 397 |
)
|
|
|
|
| 4 |
import json
|
| 5 |
import joblib
|
| 6 |
from pathlib import Path
|
| 7 |
+
from datetime import datetime
|
| 8 |
from dateutil.relativedelta import relativedelta
|
| 9 |
import plotly.express as px
|
| 10 |
import plotly.graph_objects as go
|
|
|
|
| 28 |
"""
|
| 29 |
<style>
|
| 30 |
.block-container {padding-top:2rem;padding-bottom:2rem;}
|
| 31 |
+
[data-testid="stSidebar"] {background: rgba(255,255,255,0.02);}
|
| 32 |
.card {background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);
|
| 33 |
border-radius:16px;padding:14px;margin-bottom:10px;}
|
| 34 |
+
.small-note {opacity:0.78;font-size:0.92rem;}
|
| 35 |
+
.legend-dot {display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:8px;}
|
| 36 |
+
div[data-testid="stMetricValue"] {font-size: 2rem;}
|
| 37 |
</style>
|
| 38 |
""",
|
| 39 |
unsafe_allow_html=True,
|
|
|
|
| 43 |
# LOADERS
|
| 44 |
# -------------------------------------------------------
|
| 45 |
@st.cache_data
|
| 46 |
+
def load_csv(name: str) -> pd.DataFrame:
|
| 47 |
return pd.read_csv(p(name))
|
| 48 |
|
| 49 |
@st.cache_data
|
| 50 |
+
def load_geo(name: str) -> dict:
|
| 51 |
with open(p(name), "r", encoding="utf-8") as f:
|
| 52 |
return json.load(f)
|
| 53 |
|
| 54 |
@st.cache_resource
|
| 55 |
+
def load_model(name: str):
|
| 56 |
return joblib.load(p(name))
|
| 57 |
|
| 58 |
@st.cache_data
|
| 59 |
+
def load_json(name: str):
|
| 60 |
with open(p(name), "r", encoding="utf-8") as f:
|
| 61 |
return json.load(f)
|
| 62 |
|
| 63 |
# -------------------------------------------------------
|
| 64 |
+
# STANDARDIZATION HELPERS
|
| 65 |
# -------------------------------------------------------
|
| 66 |
+
def normalize_county(x) -> str:
|
| 67 |
+
if pd.isna(x):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
return ""
|
| 69 |
+
s = str(x).strip()
|
| 70 |
+
s = " ".join(s.split())
|
| 71 |
+
s = s.replace("&", "and")
|
| 72 |
+
s = s.title()
|
| 73 |
+
s = s.replace("Elgeyo Marakwet", "Elgeyo-Marakwet")
|
| 74 |
+
return s
|
| 75 |
+
|
| 76 |
+
def detect_month_col(df: pd.DataFrame) -> str | None:
|
| 77 |
+
for c in ["month", "Month", "date", "Date", "TIME_PERIOD", "time_period", "assessment_month", "Assessment_Month"]:
|
| 78 |
+
if c in df.columns:
|
| 79 |
+
return c
|
| 80 |
+
for c in df.columns:
|
| 81 |
+
if "month" in c.lower():
|
| 82 |
+
return c
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
def detect_county_col(df: pd.DataFrame) -> str | None:
|
| 86 |
+
for c in ["county", "County", "admin1", "Admin1", "Admin 1", "Admin_1"]:
|
| 87 |
+
if c in df.columns:
|
| 88 |
+
return c
|
| 89 |
+
for c in df.columns:
|
| 90 |
+
if "county" in c.lower():
|
| 91 |
+
return c
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
def detect_risk_col(df: pd.DataFrame) -> str | None:
|
| 95 |
+
for c in ["risk_proba", "risk_probability", "Risk_Probability", "risk_prob", "probability", "proba"]:
|
| 96 |
+
if c in df.columns:
|
| 97 |
+
return c
|
| 98 |
+
for c in df.columns:
|
| 99 |
+
lc = c.lower()
|
| 100 |
+
if ("risk" in lc and "prob" in lc) or lc in ["risk", "proba", "probability"]:
|
| 101 |
+
return c
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
def coerce_month(df: pd.DataFrame) -> pd.DataFrame:
|
| 105 |
+
mcol = detect_month_col(df)
|
| 106 |
+
if mcol is not None and mcol != "month":
|
| 107 |
+
df = df.rename(columns={mcol: "month"})
|
| 108 |
+
if "month" in df.columns:
|
| 109 |
+
df["month"] = pd.to_datetime(df["month"], errors="coerce")
|
| 110 |
+
return df
|
| 111 |
+
|
| 112 |
+
def coerce_county(df: pd.DataFrame) -> pd.DataFrame:
|
| 113 |
+
ccol = detect_county_col(df)
|
| 114 |
+
if ccol is not None and ccol != "county":
|
| 115 |
+
df = df.rename(columns={ccol: "county"})
|
| 116 |
+
if "county" in df.columns:
|
| 117 |
+
df["county"] = df["county"].map(normalize_county)
|
| 118 |
+
return df
|
| 119 |
+
|
| 120 |
+
def coerce_risk(df: pd.DataFrame) -> pd.DataFrame:
|
| 121 |
+
rcol = detect_risk_col(df)
|
| 122 |
+
if rcol is not None and rcol != "risk_proba":
|
| 123 |
+
df = df.rename(columns={rcol: "risk_proba"})
|
| 124 |
+
if "risk_proba" in df.columns:
|
| 125 |
+
df["risk_proba"] = pd.to_numeric(df["risk_proba"], errors="coerce")
|
| 126 |
+
return df
|
| 127 |
|
| 128 |
# -------------------------------------------------------
|
| 129 |
+
# GEOJSON HELPERS
|
| 130 |
# -------------------------------------------------------
|
| 131 |
+
def geojson_detect_county_key(gj: dict) -> str:
|
| 132 |
+
feats = gj.get("features", [])
|
| 133 |
+
if not feats:
|
| 134 |
+
return "properties.shapeName"
|
| 135 |
+
props = feats[0].get("properties", {})
|
| 136 |
+
keys = list(props.keys())
|
| 137 |
+
|
| 138 |
+
preferred = []
|
| 139 |
+
for k in keys:
|
| 140 |
+
lk = k.lower()
|
| 141 |
+
if "shapename" in lk or (("county" in lk or "name" in lk) and "code" not in lk and "id" not in lk):
|
| 142 |
+
preferred.append(k)
|
| 143 |
+
if preferred:
|
| 144 |
+
return f"properties.{preferred[0]}"
|
| 145 |
+
|
| 146 |
+
for k in keys:
|
| 147 |
+
if isinstance(props.get(k), str):
|
| 148 |
+
return f"properties.{k}"
|
| 149 |
+
|
| 150 |
+
return "properties.shapeName"
|
| 151 |
+
|
| 152 |
+
@st.cache_data
|
| 153 |
+
def add_norm_geojson_key(gj: dict, source_key: str | None = None) -> tuple[dict, str]:
|
| 154 |
+
if source_key is None:
|
| 155 |
+
source_key = geojson_detect_county_key(gj)
|
| 156 |
+
prop_key = source_key.split(".", 1)[1] if source_key.startswith("properties.") else source_key
|
| 157 |
+
for ft in gj.get("features", []):
|
| 158 |
+
props = ft.setdefault("properties", {})
|
| 159 |
+
props["__norm_county"] = normalize_county(props.get(prop_key, ""))
|
| 160 |
+
return gj, "properties.__norm_county"
|
| 161 |
+
|
| 162 |
+
def _iter_coords(obj):
|
| 163 |
+
if isinstance(obj, (list, tuple)):
|
| 164 |
+
if len(obj) == 2 and all(isinstance(v, (int, float)) for v in obj):
|
| 165 |
+
yield obj[0], obj[1]
|
| 166 |
+
else:
|
| 167 |
+
for it in obj:
|
| 168 |
+
yield from _iter_coords(it)
|
| 169 |
+
|
| 170 |
+
def geojson_bounds(gj: dict) -> tuple[float, float, float, float]:
|
| 171 |
+
minx = miny = float("inf")
|
| 172 |
+
maxx = maxy = float("-inf")
|
| 173 |
+
for ft in gj.get("features", []):
|
| 174 |
+
geom = ft.get("geometry", {})
|
| 175 |
+
coords = geom.get("coordinates")
|
| 176 |
+
if coords is None:
|
| 177 |
+
continue
|
| 178 |
+
for x, y in _iter_coords(coords):
|
| 179 |
+
minx = min(minx, x); miny = min(miny, y)
|
| 180 |
+
maxx = max(maxx, x); maxy = max(maxy, y)
|
| 181 |
+
if minx == float("inf"):
|
| 182 |
+
return (np.nan, np.nan, np.nan, np.nan)
|
| 183 |
+
return (minx, miny, maxx, maxy)
|
| 184 |
+
|
| 185 |
+
def is_wgs84(bounds: tuple[float, float, float, float]) -> bool:
|
| 186 |
+
minx, miny, maxx, maxy = bounds
|
| 187 |
+
if any(pd.isna(v) for v in bounds):
|
| 188 |
+
return False
|
| 189 |
+
return (-180 <= minx <= 180) and (-180 <= maxx <= 180) and (-90 <= miny <= 90) and (-90 <= maxy <= 90)
|
| 190 |
|
| 191 |
# -------------------------------------------------------
|
| 192 |
# RISK BANDS + COLORS
|
| 193 |
# -------------------------------------------------------
|
| 194 |
RISK_COLORS = {
|
| 195 |
+
"Secure": "#16a34a",
|
| 196 |
+
"Watch": "#facc15",
|
| 197 |
+
"High": "#f97316",
|
| 198 |
"Extreme": "#dc2626",
|
| 199 |
+
"Unknown": "#6b7280",
|
| 200 |
}
|
| 201 |
|
| 202 |
+
RISK_ORDER = ["Secure", "Watch", "High", "Extreme", "Unknown"]
|
| 203 |
+
|
| 204 |
+
def risk_band(p: float, thr: float) -> str:
|
| 205 |
+
if pd.isna(p):
|
| 206 |
+
return "Unknown"
|
| 207 |
+
if p < thr:
|
| 208 |
return "Secure"
|
| 209 |
+
if p < min(thr + 0.15, 1.0):
|
| 210 |
return "Watch"
|
| 211 |
+
if p < min(thr + 0.35, 1.0):
|
| 212 |
return "High"
|
| 213 |
return "Extreme"
|
| 214 |
|
| 215 |
# -------------------------------------------------------
|
| 216 |
+
# TABLE STYLING
|
| 217 |
# -------------------------------------------------------
|
| 218 |
def _hex_to_rgba(hex_color: str, alpha: float = 0.18) -> str:
|
| 219 |
+
h = hex_color.lstrip("#")
|
| 220 |
+
r = int(h[0:2], 16); g = int(h[2:4], 16); b = int(h[4:6], 16)
|
|
|
|
|
|
|
|
|
|
| 221 |
return f"rgba({r},{g},{b},{alpha})"
|
| 222 |
|
| 223 |
def style_risk_table(df: pd.DataFrame) -> "pd.io.formats.style.Styler":
|
| 224 |
+
d = df.copy()
|
| 225 |
+
if "risk_proba" in d.columns:
|
| 226 |
+
d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
+
cols = [c for c in ["county", "risk_proba", "band"] if c in d.columns]
|
|
|
|
| 229 |
if cols:
|
| 230 |
+
d = d[cols]
|
| 231 |
|
| 232 |
+
sty = d.style
|
| 233 |
|
| 234 |
+
if "risk_proba" in d.columns:
|
| 235 |
sty = sty.format({"risk_proba": "{:.3f}"})
|
| 236 |
+
sty = sty.bar(subset=["risk_proba"], vmin=0.0, vmax=1.0)
|
| 237 |
|
| 238 |
+
if "band" in d.columns:
|
| 239 |
+
def band_cell(v):
|
| 240 |
+
c = RISK_COLORS.get(str(v), "#6b7280")
|
| 241 |
+
return f"background-color: {_hex_to_rgba(c, 0.22)}; font-weight:700;"
|
| 242 |
+
sty = sty.applymap(band_cell, subset=["band"])
|
| 243 |
|
|
|
|
|
|
|
|
|
|
| 244 |
sty = sty.set_properties(**{
|
| 245 |
"border": "1px solid rgba(255,255,255,0.06)",
|
| 246 |
"padding": "8px",
|
| 247 |
"font-size": "0.95rem",
|
| 248 |
+
"text-align": "left",
|
| 249 |
}).set_table_styles([
|
| 250 |
{"selector": "th", "props": [("font-weight", "700"), ("text-align", "left")]},
|
|
|
|
|
|
|
| 251 |
])
|
| 252 |
|
| 253 |
return sty
|
| 254 |
|
| 255 |
+
# -------------------------------------------------------
|
| 256 |
+
# FRIENDLY LABELS (scenario + drivers)
|
| 257 |
+
# -------------------------------------------------------
|
| 258 |
+
FRIENDLY_FEATURES = {
|
| 259 |
+
# rainfall / vegetation
|
| 260 |
+
"r3q_lag_1": "Rainfall anomaly (1-month lag)",
|
| 261 |
+
"rain_lag_1": "Rainfall level (1-month lag)",
|
| 262 |
+
"ndvi_lag_1": "Vegetation condition (NDVI, 1-month lag)",
|
| 263 |
+
"vim_lag_1": "Vegetation condition (1-month lag)",
|
| 264 |
+
"vim_lag_2": "Vegetation condition (2-month lag)",
|
| 265 |
+
"vim_lag_3": "Vegetation condition (3-month lag)",
|
| 266 |
+
|
| 267 |
+
# prices
|
| 268 |
+
"price_pct_change": "Food price change (%)",
|
| 269 |
+
"price_lag_1": "Food price level (1-month lag)",
|
| 270 |
+
"maize_price_per_kg": "Maize price (per kg)",
|
| 271 |
+
|
| 272 |
+
# conflict
|
| 273 |
+
"events_lag_1": "Conflict events (1-month lag)",
|
| 274 |
+
"fatalities_lag_1": "Conflict fatalities (1-month lag)",
|
| 275 |
+
|
| 276 |
+
# poverty / structural
|
| 277 |
+
"mpi": "Poverty index (MPI)",
|
| 278 |
+
"is_ASAL": "ASAL county (1=yes, 0=no)",
|
| 279 |
+
|
| 280 |
+
# lagged crisis flags
|
| 281 |
+
"prev_crisis_lag_1": "Previous month crisis (1=yes, 0=no)",
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
DRIVER_EXPLAIN = {
|
| 285 |
+
"r3q_lag_1": "Unusual rainfall shifts can raise stress on food systems.",
|
| 286 |
+
"rain_lag_1": "Low rainfall reduces production and water access.",
|
| 287 |
+
"ndvi_lag_1": "Poor vegetation signals weak crop/pasture conditions.",
|
| 288 |
+
"vim_lag_1": "Vegetation health reflects current production conditions.",
|
| 289 |
+
"price_pct_change": "Fast price increases reduce household purchasing power.",
|
| 290 |
+
"price_lag_1": "High food prices keep households under pressure.",
|
| 291 |
+
"events_lag_1": "More conflict disrupts markets and livelihoods.",
|
| 292 |
+
"fatalities_lag_1": "Severe insecurity increases displacement and disruption.",
|
| 293 |
+
"mpi": "Higher poverty increases vulnerability to shocks.",
|
| 294 |
+
"is_ASAL": "Arid and semi-arid areas face higher climate sensitivity.",
|
| 295 |
+
"prev_crisis_lag_1": "Recent crisis often persists into the next period.",
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
def pretty_feature_name(f: str) -> str:
|
| 299 |
+
return FRIENDLY_FEATURES.get(f, f)
|
| 300 |
+
|
| 301 |
+
def driver_sentence(f: str) -> str:
|
| 302 |
+
return DRIVER_EXPLAIN.get(f, "This factor is associated with changes in risk.")
|
| 303 |
+
|
| 304 |
+
# -------------------------------------------------------
|
| 305 |
+
# LOAD DATA
|
| 306 |
+
# -------------------------------------------------------
|
| 307 |
+
hist = load_csv("predictions_historical.csv")
|
| 308 |
+
forecast = load_csv("predictions_forecast_next_month.csv")
|
| 309 |
+
national = load_csv("national_trend.csv")
|
| 310 |
+
top10 = load_csv("top10_by_month.csv")
|
| 311 |
+
baseline = load_csv("baseline_latest_features.csv")
|
| 312 |
+
feature_importance = load_csv("feature_importance.csv")
|
| 313 |
+
geojson = load_geo("kenya_counties.geojson")
|
| 314 |
+
model = load_model("model.joblib")
|
| 315 |
+
FEATURES = load_json("features.json")
|
| 316 |
+
|
| 317 |
+
hist = coerce_month(coerce_risk(coerce_county(hist)))
|
| 318 |
+
forecast = coerce_month(coerce_risk(coerce_county(forecast)))
|
| 319 |
+
top10 = coerce_month(coerce_risk(coerce_county(top10)))
|
| 320 |
+
national = coerce_month(national)
|
| 321 |
+
baseline = coerce_county(baseline)
|
| 322 |
+
|
| 323 |
+
# national column coercion
|
| 324 |
+
if "national_avg_risk" not in national.columns:
|
| 325 |
+
rc = detect_risk_col(national)
|
| 326 |
+
if rc and rc != "national_avg_risk":
|
| 327 |
+
national = national.rename(columns={rc: "national_avg_risk"})
|
| 328 |
+
national["national_avg_risk"] = pd.to_numeric(national.get("national_avg_risk", np.nan), errors="coerce")
|
| 329 |
+
|
| 330 |
+
# feature importance coercion
|
| 331 |
+
if "feature" not in feature_importance.columns:
|
| 332 |
+
for c in feature_importance.columns:
|
| 333 |
+
if "feature" in c.lower():
|
| 334 |
+
feature_importance = feature_importance.rename(columns={c: "feature"})
|
| 335 |
+
if "importance" not in feature_importance.columns:
|
| 336 |
+
for c in feature_importance.columns:
|
| 337 |
+
if "import" in c.lower():
|
| 338 |
+
feature_importance = feature_importance.rename(columns={c: "importance"})
|
| 339 |
+
if "importance" in feature_importance.columns:
|
| 340 |
+
feature_importance["importance"] = pd.to_numeric(feature_importance["importance"], errors="coerce")
|
| 341 |
+
|
| 342 |
+
# forecast month: use file month if present, else next month from today
|
| 343 |
+
if "month" in forecast.columns and not forecast["month"].isna().all():
|
| 344 |
+
forecast_month = forecast["month"].max()
|
| 345 |
+
else:
|
| 346 |
+
forecast_month = datetime.today().replace(day=1) + relativedelta(months=1)
|
| 347 |
+
|
| 348 |
+
# latest observed month: from hist
|
| 349 |
+
if "month" not in hist.columns or hist["month"].isna().all():
|
| 350 |
+
st.error("Historical predictions file is missing a usable month column.")
|
| 351 |
+
st.stop()
|
| 352 |
+
latest_hist_month = hist["month"].max()
|
| 353 |
+
|
| 354 |
# -------------------------------------------------------
|
| 355 |
# SIDEBAR
|
| 356 |
# -------------------------------------------------------
|
|
|
|
| 360 |
|
| 361 |
page = st.sidebar.radio(
|
| 362 |
"Navigation",
|
| 363 |
+
["National Situation", "Risk Map", "Scenario Lab", "County Profile", "About"],
|
| 364 |
)
|
| 365 |
|
| 366 |
st.sidebar.markdown("### Risk Bands")
|
| 367 |
+
for k in ["Secure", "Watch", "High", "Extreme"]:
|
| 368 |
st.sidebar.markdown(
|
| 369 |
+
f"<span class='legend-dot' style='background:{RISK_COLORS[k]}'></span>{k}",
|
| 370 |
unsafe_allow_html=True,
|
| 371 |
)
|
| 372 |
+
st.sidebar.markdown(
|
| 373 |
+
"<div class='small-note'>Bands adjust when you change the threshold.</div>",
|
| 374 |
+
unsafe_allow_html=True,
|
| 375 |
+
)
|
| 376 |
|
| 377 |
# =======================================================
|
| 378 |
# NATIONAL SITUATION
|
|
|
|
| 381 |
st.title("National Risk Situation")
|
| 382 |
|
| 383 |
latest_data = hist[hist["month"] == latest_hist_month].copy()
|
| 384 |
+
latest_data["band"] = latest_data["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 385 |
|
| 386 |
+
fc_data = forecast.copy()
|
| 387 |
+
fc_data["band"] = fc_data["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 388 |
|
| 389 |
col1, col2, col3, col4 = st.columns(4)
|
| 390 |
+
col1.metric("Observed Month (Latest)", latest_hist_month.strftime("%B %Y"))
|
| 391 |
+
col2.metric("National Risk Index (Observed)", f"{latest_data['risk_proba'].mean():.2f}")
|
| 392 |
+
col3.metric("Counties Above Threshold (Observed)", int((latest_data["risk_proba"] >= threshold).sum()))
|
| 393 |
+
col4.metric("Projection Month", forecast_month.strftime("%B %Y"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
+
# trend chart
|
| 396 |
fig = go.Figure()
|
| 397 |
+
trend = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month")
|
| 398 |
+
fig.add_trace(go.Scatter(x=trend["month"], y=trend["national_avg_risk"], mode="lines", name="Observed"))
|
| 399 |
+
if not fc_data.empty:
|
| 400 |
+
proj_y = float(fc_data["risk_proba"].mean())
|
| 401 |
+
fig.add_trace(go.Scatter(x=[forecast_month], y=[proj_y], mode="markers", name="Projection"))
|
| 402 |
+
if len(trend) > 0:
|
| 403 |
+
fig.add_trace(go.Scatter(
|
| 404 |
+
x=[trend["month"].iloc[-1], forecast_month],
|
| 405 |
+
y=[trend["national_avg_risk"].iloc[-1], proj_y],
|
| 406 |
+
mode="lines",
|
| 407 |
+
line=dict(dash="dot"),
|
| 408 |
+
showlegend=False,
|
| 409 |
+
))
|
| 410 |
+
fig.add_hline(y=threshold, line_dash="dot")
|
| 411 |
+
fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
|
| 412 |
st.plotly_chart(fig, use_container_width=True)
|
| 413 |
|
| 414 |
+
# top risk: exclude Secure
|
| 415 |
+
st.subheader("Top Counties Above Threshold")
|
| 416 |
+
top_risk = (
|
| 417 |
+
latest_data[latest_data["risk_proba"] >= threshold]
|
| 418 |
+
.sort_values("risk_proba", ascending=False)
|
| 419 |
+
.head(20)[["county", "risk_proba", "band"]]
|
| 420 |
+
.copy()
|
| 421 |
+
)
|
| 422 |
+
if top_risk.empty:
|
| 423 |
+
st.info("No counties are above the current threshold in the latest observed month.")
|
| 424 |
else:
|
| 425 |
+
st.dataframe(style_risk_table(top_risk), use_container_width=True, hide_index=True)
|
| 426 |
|
| 427 |
# =======================================================
|
| 428 |
# RISK MAP
|
|
|
|
| 430 |
elif page == "Risk Map":
|
| 431 |
st.title("County Risk Map")
|
| 432 |
|
| 433 |
+
# geojson sanity check for mapbox
|
| 434 |
+
b = geojson_bounds(geojson)
|
| 435 |
+
if not is_wgs84(b):
|
| 436 |
+
st.error(
|
| 437 |
+
"Your `kenya_counties.geojson` is not in WGS84 lon/lat (EPSG:4326). "
|
| 438 |
+
"Re-export it as EPSG:4326 and redeploy."
|
| 439 |
+
)
|
| 440 |
+
st.stop()
|
| 441 |
+
|
| 442 |
+
geo_norm, featureidkey_norm = add_norm_geojson_key(geojson)
|
| 443 |
+
|
| 444 |
view = st.radio("View", ["Historical", "Forecast"], horizontal=True)
|
| 445 |
|
| 446 |
if view == "Historical":
|
| 447 |
+
months = sorted(hist["month"].dropna().unique())
|
| 448 |
+
selected_month = st.selectbox("Month", months, index=len(months) - 1)
|
| 449 |
+
df = hist[hist["month"] == selected_month].copy()
|
| 450 |
+
display_month = pd.to_datetime(selected_month)
|
| 451 |
else:
|
| 452 |
df = forecast.copy()
|
| 453 |
display_month = forecast_month
|
| 454 |
|
| 455 |
+
df["risk_proba"] = pd.to_numeric(df["risk_proba"], errors="coerce")
|
| 456 |
+
df["band"] = df["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 457 |
+
df["county_norm"] = df["county"].map(normalize_county)
|
| 458 |
+
|
| 459 |
+
st.markdown(f"**Displaying:** {display_month.strftime('%B %Y')}")
|
| 460 |
+
|
| 461 |
+
left, right = st.columns([2.2, 1.0], gap="large")
|
| 462 |
+
|
| 463 |
+
with left:
|
| 464 |
+
fig = px.choropleth_mapbox(
|
| 465 |
+
df.dropna(subset=["county_norm"]),
|
| 466 |
+
geojson=geo_norm,
|
| 467 |
+
locations="county_norm",
|
| 468 |
+
featureidkey=featureidkey_norm,
|
| 469 |
+
color="band",
|
| 470 |
+
category_orders={"band": RISK_ORDER},
|
| 471 |
+
color_discrete_map=RISK_COLORS,
|
| 472 |
+
hover_name="county",
|
| 473 |
+
hover_data={"risk_proba": ":.3f"},
|
| 474 |
+
mapbox_style="carto-positron",
|
| 475 |
+
zoom=5.2,
|
| 476 |
+
center={"lat": 0.2, "lon": 37.8},
|
| 477 |
+
height=650,
|
| 478 |
+
)
|
| 479 |
+
# remove legend next to map (sidebar already has it)
|
| 480 |
+
fig.update_layout(showlegend=False, margin=dict(l=10, r=10, t=10, b=10))
|
| 481 |
+
fig.update_traces(marker_line_width=0.8)
|
| 482 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 483 |
+
|
| 484 |
+
with right:
|
| 485 |
+
st.subheader("Counties Sorted by Risk")
|
| 486 |
+
ranked = df.sort_values("risk_proba", ascending=False)[["county", "risk_proba", "band"]].copy()
|
| 487 |
+
|
| 488 |
+
# optional filter: avoid listing Secure rows unless user wants them
|
| 489 |
+
show_secure = st.checkbox("Include Secure counties", value=False)
|
| 490 |
+
if not show_secure:
|
| 491 |
+
ranked = ranked[ranked["band"] != "Secure"].copy()
|
| 492 |
|
| 493 |
+
if ranked.empty:
|
| 494 |
+
st.info("No counties to show under the current filter/threshold.")
|
| 495 |
+
else:
|
| 496 |
+
st.dataframe(style_risk_table(ranked), use_container_width=True, height=650, hide_index=True)
|
| 497 |
|
| 498 |
# =======================================================
|
| 499 |
+
# SCENARIO LAB
|
| 500 |
# =======================================================
|
| 501 |
+
elif page == "Scenario Lab":
|
| 502 |
st.title("Scenario Simulation")
|
| 503 |
|
| 504 |
+
if "county" not in baseline.columns:
|
| 505 |
+
st.error("baseline_latest_features.csv is missing a county column.")
|
| 506 |
+
st.stop()
|
| 507 |
+
|
| 508 |
+
counties = sorted([c for c in baseline["county"].dropna().unique() if c])
|
| 509 |
county = st.selectbox("Select County", counties)
|
| 510 |
|
| 511 |
base_row = baseline[baseline["county"] == county].copy()
|
| 512 |
if base_row.empty:
|
| 513 |
+
st.error("No baseline row found for this county.")
|
| 514 |
st.stop()
|
| 515 |
|
| 516 |
+
# ensure all model features exist
|
| 517 |
+
for f in FEATURES:
|
| 518 |
+
if f not in base_row.columns:
|
| 519 |
+
base_row[f] = np.nan
|
| 520 |
+
|
| 521 |
x_base = base_row.iloc[[0]][FEATURES].copy()
|
| 522 |
x_edit = x_base.copy()
|
| 523 |
|
| 524 |
+
st.markdown("<div class='small-note'>Adjust inputs, then run the upcoming-month prediction.</div>", unsafe_allow_html=True)
|
| 525 |
|
| 526 |
+
# Quick controls (only if present)
|
| 527 |
+
c1, c2 = st.columns(2)
|
| 528 |
+
with c1:
|
| 529 |
+
if "r3q_lag_1" in x_edit.columns:
|
| 530 |
+
x_edit["r3q_lag_1"] = st.number_input(
|
| 531 |
+
pretty_feature_name("r3q_lag_1"),
|
| 532 |
+
value=float(x_edit["r3q_lag_1"].iloc[0]) if pd.notna(x_edit["r3q_lag_1"].iloc[0]) else 0.0
|
| 533 |
+
)
|
| 534 |
+
if "ndvi_lag_1" in x_edit.columns:
|
| 535 |
+
x_edit["ndvi_lag_1"] = st.number_input(
|
| 536 |
+
pretty_feature_name("ndvi_lag_1"),
|
| 537 |
+
value=float(x_edit["ndvi_lag_1"].iloc[0]) if pd.notna(x_edit["ndvi_lag_1"].iloc[0]) else 0.0
|
| 538 |
+
)
|
| 539 |
+
with c2:
|
| 540 |
+
if "price_pct_change" in x_edit.columns:
|
| 541 |
+
x_edit["price_pct_change"] = st.number_input(
|
| 542 |
+
pretty_feature_name("price_pct_change"),
|
| 543 |
+
value=float(x_edit["price_pct_change"].iloc[0]) if pd.notna(x_edit["price_pct_change"].iloc[0]) else 0.0
|
| 544 |
+
)
|
| 545 |
+
if "events_lag_1" in x_edit.columns:
|
| 546 |
+
x_edit["events_lag_1"] = st.number_input(
|
| 547 |
+
pretty_feature_name("events_lag_1"),
|
| 548 |
+
value=float(x_edit["events_lag_1"].iloc[0]) if pd.notna(x_edit["events_lag_1"].iloc[0]) else 0.0
|
| 549 |
+
)
|
| 550 |
|
| 551 |
+
with st.expander("Advanced: Edit all drivers (stakeholder-friendly labels)"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
for f in FEATURES:
|
| 553 |
+
label = pretty_feature_name(f)
|
| 554 |
+
cur = x_edit[f].iloc[0]
|
| 555 |
+
val = st.number_input(
|
| 556 |
+
label,
|
| 557 |
+
value=float(cur) if pd.notna(cur) else 0.0,
|
| 558 |
+
key=f"adv_{county}_{f}",
|
| 559 |
+
)
|
| 560 |
+
x_edit[f] = val
|
| 561 |
|
| 562 |
if st.button("Run Prediction", use_container_width=True):
|
| 563 |
+
try:
|
| 564 |
+
base_prob = float(model.predict_proba(x_base)[0][1])
|
| 565 |
+
new_prob = float(model.predict_proba(x_edit)[0][1])
|
| 566 |
+
delta = new_prob - base_prob
|
| 567 |
|
| 568 |
+
b1, b2, b3 = st.columns(3)
|
| 569 |
+
b1.metric("Baseline Probability", f"{base_prob:.4f}")
|
| 570 |
+
b2.metric("Scenario Probability", f"{new_prob:.4f}")
|
| 571 |
+
b3.metric("Change (Δ)", f"{delta:.4f}")
|
| 572 |
|
| 573 |
+
bnd = risk_band(new_prob, threshold)
|
| 574 |
+
st.markdown(f"**Risk Band:** {bnd}")
|
| 575 |
+
|
| 576 |
+
except Exception as e:
|
| 577 |
+
st.error(f"Prediction failed (model/features mismatch): {e}")
|
| 578 |
|
| 579 |
# =======================================================
|
| 580 |
# COUNTY PROFILE
|
|
|
|
| 582 |
elif page == "County Profile":
|
| 583 |
st.title("County Profile")
|
| 584 |
|
| 585 |
+
counties = sorted(hist["county"].dropna().unique())
|
| 586 |
county = st.selectbox("Select County", counties)
|
| 587 |
|
| 588 |
+
hist_c = hist[hist["county"] == county].sort_values("month").copy()
|
| 589 |
+
hist_c = hist_c.dropna(subset=["month", "risk_proba"])
|
| 590 |
+
|
| 591 |
+
fc_c = forecast[forecast["county"] == county].copy() if "county" in forecast.columns else pd.DataFrame()
|
| 592 |
|
| 593 |
+
# build series for plot incl projection point (if available)
|
| 594 |
fig = go.Figure()
|
| 595 |
+
fig.add_trace(go.Scatter(
|
| 596 |
+
x=hist_c["month"],
|
| 597 |
+
y=hist_c["risk_proba"],
|
| 598 |
+
mode="lines+markers",
|
| 599 |
+
name="Observed",
|
| 600 |
+
))
|
| 601 |
+
|
| 602 |
+
if not fc_c.empty and "risk_proba" in fc_c.columns:
|
| 603 |
+
fc_val = float(pd.to_numeric(fc_c["risk_proba"], errors="coerce").iloc[0])
|
| 604 |
+
fig.add_trace(go.Scatter(
|
| 605 |
+
x=[forecast_month],
|
| 606 |
+
y=[fc_val],
|
| 607 |
+
mode="markers",
|
| 608 |
+
name="Projection",
|
| 609 |
+
))
|
| 610 |
+
if len(hist_c) > 0:
|
| 611 |
+
fig.add_trace(go.Scatter(
|
| 612 |
+
x=[hist_c["month"].iloc[-1], forecast_month],
|
| 613 |
+
y=[float(hist_c["risk_proba"].iloc[-1]), fc_val],
|
| 614 |
+
mode="lines",
|
| 615 |
+
line=dict(dash="dot"),
|
| 616 |
+
showlegend=False,
|
| 617 |
+
))
|
| 618 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 619 |
fig.add_hline(y=threshold, line_dash="dot")
|
| 620 |
+
fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
|
| 621 |
st.plotly_chart(fig, use_container_width=True)
|
| 622 |
|
| 623 |
+
# latest metrics
|
| 624 |
+
c1, c2, c3 = st.columns(3)
|
| 625 |
+
latest_obs = float(hist_c["risk_proba"].iloc[-1]) if not hist_c.empty else np.nan
|
| 626 |
+
c1.metric("Latest Observed Risk", f"{latest_obs:.2f}" if np.isfinite(latest_obs) else "N/A")
|
| 627 |
+
c2.metric("Observed Month (Latest)", hist_c["month"].iloc[-1].strftime("%B %Y") if not hist_c.empty else "N/A")
|
| 628 |
+
if not fc_c.empty and "risk_proba" in fc_c.columns:
|
| 629 |
+
fc_val = float(pd.to_numeric(fc_c["risk_proba"], errors="coerce").iloc[0])
|
| 630 |
+
c3.metric("Projected Risk", f"{fc_val:.2f}")
|
| 631 |
+
else:
|
| 632 |
+
c3.metric("Projected Risk", "N/A")
|
| 633 |
|
| 634 |
+
# drivers - short stakeholder-friendly bullets
|
| 635 |
st.subheader("Key Drivers (Plain Language)")
|
| 636 |
+
if "feature" in feature_importance.columns and "importance" in feature_importance.columns:
|
| 637 |
+
top_drivers = (
|
| 638 |
+
feature_importance.dropna(subset=["feature", "importance"])
|
| 639 |
+
.sort_values("importance", ascending=False)
|
| 640 |
+
.head(6)
|
| 641 |
+
)
|
| 642 |
+
for _, r in top_drivers.iterrows():
|
| 643 |
+
f = str(r["feature"])
|
| 644 |
+
st.markdown(f"- **{pretty_feature_name(f)}** — {driver_sentence(f)}")
|
| 645 |
+
else:
|
| 646 |
+
st.info("feature_importance.csv is missing expected columns (feature, importance).")
|
| 647 |
|
| 648 |
# =======================================================
|
| 649 |
# ABOUT
|
|
|
|
| 654 |
f"""
|
| 655 |
This dashboard forecasts IPC Phase 3+ (Crisis) risk at county level.
|
| 656 |
|
| 657 |
+
- **National Situation:** observed month vs projected month.
|
| 658 |
+
- **Risk Map:** spatial distribution with a ranked list beside the map.
|
| 659 |
+
- **Scenario Lab:** adjust conditions and re-run the model.
|
| 660 |
+
- **County Profile:** observed trend plus projection point.
|
| 661 |
|
| 662 |
+
Projection month currently available for: **{forecast_month.strftime("%B %Y")}**
|
| 663 |
"""
|
| 664 |
)
|