Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +80 -49
src/streamlit_app.py
CHANGED
|
@@ -26,7 +26,7 @@ st.set_page_config(
|
|
| 26 |
)
|
| 27 |
|
| 28 |
# -------------------------------------------------------
|
| 29 |
-
# LIGHT CSS
|
| 30 |
# -------------------------------------------------------
|
| 31 |
st.markdown(
|
| 32 |
"""
|
|
@@ -38,6 +38,7 @@ st.markdown(
|
|
| 38 |
.card {background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06);
|
| 39 |
border-radius: 16px; padding: 14px; margin-bottom: 10px;}
|
| 40 |
.legend-dot {display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:8px;}
|
|
|
|
| 41 |
</style>
|
| 42 |
""",
|
| 43 |
unsafe_allow_html=True,
|
|
@@ -74,12 +75,8 @@ def normalize_county_name(x: str) -> str:
|
|
| 74 |
s = " ".join(s.split())
|
| 75 |
s = s.replace("&", "and")
|
| 76 |
s = s.title()
|
| 77 |
-
|
| 78 |
-
# Common fixes / harmonization
|
| 79 |
s = s.replace("Elgeyo Marakwet", "Elgeyo-Marakwet")
|
| 80 |
s = s.replace("Elgeyo-Marakwet", "Elgeyo-Marakwet")
|
| 81 |
-
s = s.replace("Tharaka Nithi", "Tharaka Nithi")
|
| 82 |
-
s = s.replace("Tana River", "Tana River")
|
| 83 |
return s
|
| 84 |
|
| 85 |
def detect_month_col(df: pd.DataFrame) -> str | None:
|
|
@@ -164,12 +161,8 @@ def geojson_detect_county_key(gj: dict) -> str:
|
|
| 164 |
|
| 165 |
@st.cache_data
|
| 166 |
def add_normalized_geojson_key(gj: dict, source_key: str | None = None) -> tuple[dict, str]:
|
| 167 |
-
"""
|
| 168 |
-
Adds properties.__norm_county to each feature so we can join reliably.
|
| 169 |
-
Returns (geojson_with_norm, featureidkey_to_use).
|
| 170 |
-
"""
|
| 171 |
if source_key is None:
|
| 172 |
-
source_key = geojson_detect_county_key(gj)
|
| 173 |
|
| 174 |
prop_key = source_key.split(".", 1)[1] if source_key.startswith("properties.") else source_key
|
| 175 |
|
|
@@ -180,17 +173,48 @@ def add_normalized_geojson_key(gj: dict, source_key: str | None = None) -> tuple
|
|
| 180 |
|
| 181 |
return gj, "properties.__norm_county"
|
| 182 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
# -------------------------------------------------------
|
| 184 |
# COLOR + BANDING (threshold-aware)
|
| 185 |
# -------------------------------------------------------
|
| 186 |
def risk_band(p: float, thr: float) -> str:
|
| 187 |
-
"""
|
| 188 |
-
Bands adapt to the threshold slider.
|
| 189 |
-
Secure: below threshold
|
| 190 |
-
Watch: threshold .. threshold+0.15
|
| 191 |
-
High: threshold+0.15 .. threshold+0.35
|
| 192 |
-
Extreme: threshold+0.35+
|
| 193 |
-
"""
|
| 194 |
if pd.isna(p):
|
| 195 |
return "Unknown"
|
| 196 |
if p < thr:
|
|
@@ -201,6 +225,7 @@ def risk_band(p: float, thr: float) -> str:
|
|
| 201 |
return "High"
|
| 202 |
return "Extreme"
|
| 203 |
|
|
|
|
| 204 |
RISK_COLORS = {
|
| 205 |
"Secure": "#16a34a", # green
|
| 206 |
"Watch": "#facc15", # yellow
|
|
@@ -209,7 +234,9 @@ RISK_COLORS = {
|
|
| 209 |
"Unknown": "#6b7280", # gray
|
| 210 |
}
|
| 211 |
|
| 212 |
-
|
|
|
|
|
|
|
| 213 |
d = df.copy()
|
| 214 |
if "risk_proba" in d.columns:
|
| 215 |
d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce")
|
|
@@ -244,12 +271,10 @@ geojson = load_geojson("kenya_counties.geojson")
|
|
| 244 |
model = load_model("model.joblib")
|
| 245 |
FEATURES = load_features("features.json")
|
| 246 |
|
| 247 |
-
# Standardize key frames
|
| 248 |
hist = coerce_month(coerce_risk(coerce_county(hist)))
|
| 249 |
forecast = coerce_month(coerce_risk(coerce_county(forecast)))
|
| 250 |
top10 = coerce_month(coerce_risk(coerce_county(top10)))
|
| 251 |
|
| 252 |
-
# National trend robustness
|
| 253 |
national = coerce_month(national)
|
| 254 |
if "national_avg_risk" not in national.columns:
|
| 255 |
rc = detect_risk_col(national)
|
|
@@ -257,10 +282,8 @@ if "national_avg_risk" not in national.columns:
|
|
| 257 |
national = national.rename(columns={rc: "national_avg_risk"})
|
| 258 |
national["national_avg_risk"] = pd.to_numeric(national.get("national_avg_risk", np.nan), errors="coerce")
|
| 259 |
|
| 260 |
-
# Baseline must have county column
|
| 261 |
baseline = coerce_county(baseline)
|
| 262 |
|
| 263 |
-
# Feature importance robustness
|
| 264 |
if "feature" not in feature_importance.columns:
|
| 265 |
for c in feature_importance.columns:
|
| 266 |
if "feature" in c.lower():
|
|
@@ -272,7 +295,6 @@ if "importance" not in feature_importance.columns:
|
|
| 272 |
if "importance" in feature_importance.columns:
|
| 273 |
feature_importance["importance"] = pd.to_numeric(feature_importance["importance"], errors="coerce")
|
| 274 |
|
| 275 |
-
# Forecast month: next month from today
|
| 276 |
forecast_month = (datetime.today().replace(day=1) + relativedelta(months=1))
|
| 277 |
|
| 278 |
# -------------------------------------------------------
|
|
@@ -299,11 +321,9 @@ IPC_PHASE_COLORS = {
|
|
| 299 |
|
| 300 |
def style_ipc_table(df: pd.DataFrame):
|
| 301 |
d = df.copy()
|
| 302 |
-
|
| 303 |
def row_style(row):
|
| 304 |
c = IPC_PHASE_COLORS.get(int(row["IPC Phase"]), "#6b7280")
|
| 305 |
return [f"background-color: {c}22; border-left: 6px solid {c};"] * len(row)
|
| 306 |
-
|
| 307 |
sty = d.style.apply(row_style, axis=1)
|
| 308 |
try:
|
| 309 |
sty = sty.hide(axis="index")
|
|
@@ -335,7 +355,6 @@ page = st.sidebar.radio(
|
|
| 335 |
],
|
| 336 |
)
|
| 337 |
|
| 338 |
-
# Sidebar legend (threshold-aware)
|
| 339 |
st.sidebar.markdown("### Risk Bands")
|
| 340 |
for k in ["Secure", "Watch", "High", "Extreme"]:
|
| 341 |
st.sidebar.markdown(
|
|
@@ -366,7 +385,6 @@ if page == "National Situation":
|
|
| 366 |
col3.metric("Forecast Projection", forecast_month.strftime("%B %Y"))
|
| 367 |
|
| 368 |
fig = go.Figure()
|
| 369 |
-
|
| 370 |
nat = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month")
|
| 371 |
fig.add_trace(go.Scatter(
|
| 372 |
x=nat["month"],
|
|
@@ -375,7 +393,6 @@ if page == "National Situation":
|
|
| 375 |
name="Historical",
|
| 376 |
))
|
| 377 |
|
| 378 |
-
proj_y = None
|
| 379 |
if not forecast.empty and "risk_proba" in forecast.columns:
|
| 380 |
proj_y = float(forecast["risk_proba"].mean())
|
| 381 |
fig.add_trace(go.Scatter(
|
|
@@ -384,13 +401,10 @@ if page == "National Situation":
|
|
| 384 |
mode="markers",
|
| 385 |
name="Projection",
|
| 386 |
))
|
| 387 |
-
|
| 388 |
if len(nat) > 0:
|
| 389 |
-
last_x = nat["month"].iloc[-1]
|
| 390 |
-
last_y = nat["national_avg_risk"].iloc[-1]
|
| 391 |
fig.add_trace(go.Scatter(
|
| 392 |
-
x=[
|
| 393 |
-
y=[
|
| 394 |
mode="lines",
|
| 395 |
line=dict(dash="dot"),
|
| 396 |
showlegend=False,
|
|
@@ -400,7 +414,7 @@ if page == "National Situation":
|
|
| 400 |
fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
|
| 401 |
st.plotly_chart(fig, use_container_width=True)
|
| 402 |
|
| 403 |
-
st.subheader("Top Risk Counties
|
| 404 |
top_current = latest_data.sort_values("risk_proba", ascending=False).head(15)[["county", "risk_proba"]].copy()
|
| 405 |
top_current["band"] = top_current["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 406 |
_, top_sty = styled_df_for_display(top_current, threshold)
|
|
@@ -419,6 +433,27 @@ elif page == "Spatial Intelligence":
|
|
| 419 |
st.error("Historical predictions file is missing a usable month column.")
|
| 420 |
st.stop()
|
| 421 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
months = sorted(hist["month"].dropna().unique())
|
| 423 |
selected_month = st.selectbox("Select Month", months, index=len(months) - 1)
|
| 424 |
|
|
@@ -429,6 +464,7 @@ elif page == "Spatial Intelligence":
|
|
| 429 |
)
|
| 430 |
|
| 431 |
data_month = hist[hist["month"] == selected_month].copy()
|
|
|
|
| 432 |
data_month["band"] = data_month["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 433 |
data_month["class"] = np.where(data_month["risk_proba"] >= threshold, "At Risk", "Secure")
|
| 434 |
data_month["county_norm"] = data_month["county"].map(normalize_county_name)
|
|
@@ -441,7 +477,6 @@ elif page == "Spatial Intelligence":
|
|
| 441 |
# Normalize GeoJSON join key
|
| 442 |
geojson_norm, featureidkey_norm = add_normalized_geojson_key(geojson)
|
| 443 |
|
| 444 |
-
# Join quality check
|
| 445 |
geo_norm_set = {ft.get("properties", {}).get("__norm_county", "") for ft in geojson_norm.get("features", [])}
|
| 446 |
join_ok = data_month["county_norm"].isin(geo_norm_set).mean() if len(data_month) else 0.0
|
| 447 |
if join_ok < 0.98:
|
|
@@ -450,29 +485,31 @@ elif page == "Spatial Intelligence":
|
|
| 450 |
left, right = st.columns([2.2, 1.0], gap="large")
|
| 451 |
|
| 452 |
with left:
|
|
|
|
| 453 |
fig = px.choropleth(
|
| 454 |
data_month.dropna(subset=["county_norm"]),
|
| 455 |
geojson=geojson_norm,
|
| 456 |
locations="county_norm",
|
| 457 |
featureidkey=featureidkey_norm,
|
| 458 |
-
color="
|
| 459 |
-
|
|
|
|
| 460 |
hover_name="county",
|
| 461 |
hover_data={"risk_proba": ":.3f", "band": True, "county_norm": False},
|
| 462 |
)
|
| 463 |
-
fig.update_traces(marker_line_width=
|
| 464 |
fig.update_geos(fitbounds="locations", visible=False)
|
| 465 |
-
fig.update_layout(height=620, margin=dict(l=10, r=10, t=10, b=10))
|
| 466 |
st.plotly_chart(fig, use_container_width=True)
|
| 467 |
|
| 468 |
-
with st.expander("IPC Phase Classification Reference
|
| 469 |
try:
|
| 470 |
st.dataframe(style_ipc_table(ipc_table), use_container_width=True, hide_index=True)
|
| 471 |
except TypeError:
|
| 472 |
st.dataframe(style_ipc_table(ipc_table), use_container_width=True)
|
| 473 |
|
| 474 |
with right:
|
| 475 |
-
st.markdown("#### Counties Sorted by Risk
|
| 476 |
ranked = data_month.sort_values("risk_proba", ascending=False)[["county", "risk_proba"]].copy()
|
| 477 |
ranked["band"] = ranked["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 478 |
_, ranked_sty = styled_df_for_display(ranked, threshold)
|
|
@@ -505,7 +542,6 @@ elif page == "Scenario Lab":
|
|
| 505 |
st.error("No baseline row found for this county.")
|
| 506 |
st.stop()
|
| 507 |
|
| 508 |
-
# Ensure all FEATURES exist
|
| 509 |
for f in FEATURES:
|
| 510 |
if f not in base_row.columns:
|
| 511 |
base_row[f] = np.nan
|
|
@@ -521,13 +557,9 @@ elif page == "Scenario Lab":
|
|
| 521 |
def edit_feature(col, label, default_val, lo, hi, step):
|
| 522 |
if col not in x.columns:
|
| 523 |
return
|
| 524 |
-
|
| 525 |
dv = float(default_val) if pd.notna(default_val) else 0.0
|
| 526 |
-
|
| 527 |
-
# Expand bounds to include baseline default (prevents StreamlitValueAboveMaxError)
|
| 528 |
lo2 = min(float(lo), dv)
|
| 529 |
hi2 = max(float(hi), dv)
|
| 530 |
-
|
| 531 |
val = st.number_input(
|
| 532 |
label,
|
| 533 |
value=float(dv),
|
|
@@ -569,7 +601,6 @@ elif page == "Scenario Lab":
|
|
| 569 |
color = RISK_COLORS.get(band, "#6b7280")
|
| 570 |
|
| 571 |
st.metric("Predicted Risk Probability (IPC Phase 3+)", f"{proba:.2f}")
|
| 572 |
-
|
| 573 |
st.markdown(
|
| 574 |
f"<div class='card'><b>Risk Band:</b> "
|
| 575 |
f"<span style='color:{color}; font-weight:800'>{band}</span></div>",
|
|
@@ -625,7 +656,7 @@ elif page == "County Intelligence Brief":
|
|
| 625 |
fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
|
| 626 |
st.plotly_chart(fig, use_container_width=True)
|
| 627 |
|
| 628 |
-
st.subheader("Historical Levels
|
| 629 |
tbl = county_data[["month", "risk_proba"]].copy()
|
| 630 |
tbl["band"] = tbl["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 631 |
tbl = tbl.sort_values("month", ascending=False)
|
|
@@ -677,7 +708,7 @@ elif page == "About":
|
|
| 677 |
"""
|
| 678 |
)
|
| 679 |
|
| 680 |
-
st.subheader("IPC Phase Classification Reference
|
| 681 |
try:
|
| 682 |
st.dataframe(style_ipc_table(ipc_table), use_container_width=True, hide_index=True)
|
| 683 |
except TypeError:
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
# -------------------------------------------------------
|
| 29 |
+
# LIGHT CSS
|
| 30 |
# -------------------------------------------------------
|
| 31 |
st.markdown(
|
| 32 |
"""
|
|
|
|
| 38 |
.card {background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06);
|
| 39 |
border-radius: 16px; padding: 14px; margin-bottom: 10px;}
|
| 40 |
.legend-dot {display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:8px;}
|
| 41 |
+
code {font-size: 0.95em;}
|
| 42 |
</style>
|
| 43 |
""",
|
| 44 |
unsafe_allow_html=True,
|
|
|
|
| 75 |
s = " ".join(s.split())
|
| 76 |
s = s.replace("&", "and")
|
| 77 |
s = s.title()
|
|
|
|
|
|
|
| 78 |
s = s.replace("Elgeyo Marakwet", "Elgeyo-Marakwet")
|
| 79 |
s = s.replace("Elgeyo-Marakwet", "Elgeyo-Marakwet")
|
|
|
|
|
|
|
| 80 |
return s
|
| 81 |
|
| 82 |
def detect_month_col(df: pd.DataFrame) -> str | None:
|
|
|
|
| 161 |
|
| 162 |
@st.cache_data
|
| 163 |
def add_normalized_geojson_key(gj: dict, source_key: str | None = None) -> tuple[dict, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
if source_key is None:
|
| 165 |
+
source_key = geojson_detect_county_key(gj)
|
| 166 |
|
| 167 |
prop_key = source_key.split(".", 1)[1] if source_key.startswith("properties.") else source_key
|
| 168 |
|
|
|
|
| 173 |
|
| 174 |
return gj, "properties.__norm_county"
|
| 175 |
|
| 176 |
+
def _iter_coords(obj):
|
| 177 |
+
"""Yield (x,y) coords recursively from GeoJSON geometry."""
|
| 178 |
+
if isinstance(obj, (list, tuple)):
|
| 179 |
+
# coordinate pair
|
| 180 |
+
if len(obj) == 2 and all(isinstance(v, (int, float)) for v in obj):
|
| 181 |
+
yield obj[0], obj[1]
|
| 182 |
+
else:
|
| 183 |
+
for it in obj:
|
| 184 |
+
yield from _iter_coords(it)
|
| 185 |
+
|
| 186 |
+
def geojson_coord_bounds(gj: dict) -> tuple[float, float, float, float]:
|
| 187 |
+
"""Compute (minx, miny, maxx, maxy) for quick CRS sanity check."""
|
| 188 |
+
minx = miny = float("inf")
|
| 189 |
+
maxx = maxy = float("-inf")
|
| 190 |
+
|
| 191 |
+
for ft in gj.get("features", []):
|
| 192 |
+
geom = ft.get("geometry", {})
|
| 193 |
+
coords = geom.get("coordinates", None)
|
| 194 |
+
if coords is None:
|
| 195 |
+
continue
|
| 196 |
+
for x, y in _iter_coords(coords):
|
| 197 |
+
minx = min(minx, x)
|
| 198 |
+
miny = min(miny, y)
|
| 199 |
+
maxx = max(maxx, x)
|
| 200 |
+
maxy = max(maxy, y)
|
| 201 |
+
|
| 202 |
+
if minx == float("inf"):
|
| 203 |
+
return (np.nan, np.nan, np.nan, np.nan)
|
| 204 |
+
|
| 205 |
+
return (minx, miny, maxx, maxy)
|
| 206 |
+
|
| 207 |
+
def geojson_is_wgs84(bounds: tuple[float, float, float, float]) -> bool:
|
| 208 |
+
"""Plotly choropleth needs lon/lat ranges."""
|
| 209 |
+
minx, miny, maxx, maxy = bounds
|
| 210 |
+
if any(pd.isna(v) for v in bounds):
|
| 211 |
+
return False
|
| 212 |
+
return (-180 <= minx <= 180) and (-180 <= maxx <= 180) and (-90 <= miny <= 90) and (-90 <= maxy <= 90)
|
| 213 |
+
|
| 214 |
# -------------------------------------------------------
|
| 215 |
# COLOR + BANDING (threshold-aware)
|
| 216 |
# -------------------------------------------------------
|
| 217 |
def risk_band(p: float, thr: float) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
if pd.isna(p):
|
| 219 |
return "Unknown"
|
| 220 |
if p < thr:
|
|
|
|
| 225 |
return "High"
|
| 226 |
return "Extreme"
|
| 227 |
|
| 228 |
+
# Required mapping: Secure green, Extreme red
|
| 229 |
RISK_COLORS = {
|
| 230 |
"Secure": "#16a34a", # green
|
| 231 |
"Watch": "#facc15", # yellow
|
|
|
|
| 234 |
"Unknown": "#6b7280", # gray
|
| 235 |
}
|
| 236 |
|
| 237 |
+
RISK_ORDER = ["Secure", "Watch", "High", "Extreme", "Unknown"]
|
| 238 |
+
|
| 239 |
+
def styled_df_for_display(df: pd.DataFrame, thr: float):
|
| 240 |
d = df.copy()
|
| 241 |
if "risk_proba" in d.columns:
|
| 242 |
d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce")
|
|
|
|
| 271 |
model = load_model("model.joblib")
|
| 272 |
FEATURES = load_features("features.json")
|
| 273 |
|
|
|
|
| 274 |
hist = coerce_month(coerce_risk(coerce_county(hist)))
|
| 275 |
forecast = coerce_month(coerce_risk(coerce_county(forecast)))
|
| 276 |
top10 = coerce_month(coerce_risk(coerce_county(top10)))
|
| 277 |
|
|
|
|
| 278 |
national = coerce_month(national)
|
| 279 |
if "national_avg_risk" not in national.columns:
|
| 280 |
rc = detect_risk_col(national)
|
|
|
|
| 282 |
national = national.rename(columns={rc: "national_avg_risk"})
|
| 283 |
national["national_avg_risk"] = pd.to_numeric(national.get("national_avg_risk", np.nan), errors="coerce")
|
| 284 |
|
|
|
|
| 285 |
baseline = coerce_county(baseline)
|
| 286 |
|
|
|
|
| 287 |
if "feature" not in feature_importance.columns:
|
| 288 |
for c in feature_importance.columns:
|
| 289 |
if "feature" in c.lower():
|
|
|
|
| 295 |
if "importance" in feature_importance.columns:
|
| 296 |
feature_importance["importance"] = pd.to_numeric(feature_importance["importance"], errors="coerce")
|
| 297 |
|
|
|
|
| 298 |
forecast_month = (datetime.today().replace(day=1) + relativedelta(months=1))
|
| 299 |
|
| 300 |
# -------------------------------------------------------
|
|
|
|
| 321 |
|
| 322 |
def style_ipc_table(df: pd.DataFrame):
|
| 323 |
d = df.copy()
|
|
|
|
| 324 |
def row_style(row):
|
| 325 |
c = IPC_PHASE_COLORS.get(int(row["IPC Phase"]), "#6b7280")
|
| 326 |
return [f"background-color: {c}22; border-left: 6px solid {c};"] * len(row)
|
|
|
|
| 327 |
sty = d.style.apply(row_style, axis=1)
|
| 328 |
try:
|
| 329 |
sty = sty.hide(axis="index")
|
|
|
|
| 355 |
],
|
| 356 |
)
|
| 357 |
|
|
|
|
| 358 |
st.sidebar.markdown("### Risk Bands")
|
| 359 |
for k in ["Secure", "Watch", "High", "Extreme"]:
|
| 360 |
st.sidebar.markdown(
|
|
|
|
| 385 |
col3.metric("Forecast Projection", forecast_month.strftime("%B %Y"))
|
| 386 |
|
| 387 |
fig = go.Figure()
|
|
|
|
| 388 |
nat = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month")
|
| 389 |
fig.add_trace(go.Scatter(
|
| 390 |
x=nat["month"],
|
|
|
|
| 393 |
name="Historical",
|
| 394 |
))
|
| 395 |
|
|
|
|
| 396 |
if not forecast.empty and "risk_proba" in forecast.columns:
|
| 397 |
proj_y = float(forecast["risk_proba"].mean())
|
| 398 |
fig.add_trace(go.Scatter(
|
|
|
|
| 401 |
mode="markers",
|
| 402 |
name="Projection",
|
| 403 |
))
|
|
|
|
| 404 |
if len(nat) > 0:
|
|
|
|
|
|
|
| 405 |
fig.add_trace(go.Scatter(
|
| 406 |
+
x=[nat["month"].iloc[-1], forecast_month],
|
| 407 |
+
y=[nat["national_avg_risk"].iloc[-1], proj_y],
|
| 408 |
mode="lines",
|
| 409 |
line=dict(dash="dot"),
|
| 410 |
showlegend=False,
|
|
|
|
| 414 |
fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
|
| 415 |
st.plotly_chart(fig, use_container_width=True)
|
| 416 |
|
| 417 |
+
st.subheader("Top Risk Counties")
|
| 418 |
top_current = latest_data.sort_values("risk_proba", ascending=False).head(15)[["county", "risk_proba"]].copy()
|
| 419 |
top_current["band"] = top_current["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 420 |
_, top_sty = styled_df_for_display(top_current, threshold)
|
|
|
|
| 433 |
st.error("Historical predictions file is missing a usable month column.")
|
| 434 |
st.stop()
|
| 435 |
|
| 436 |
+
# GeoJSON CRS sanity check (THIS is what fixes the blank map)
|
| 437 |
+
bounds = geojson_coord_bounds(geojson)
|
| 438 |
+
if not geojson_is_wgs84(bounds):
|
| 439 |
+
st.error(
|
| 440 |
+
"Your `kenya_counties.geojson` is not in WGS84 lon/lat (EPSG:4326). "
|
| 441 |
+
"Plotly cannot render the map with projected (meter-based) coordinates."
|
| 442 |
+
)
|
| 443 |
+
st.markdown(
|
| 444 |
+
f"""
|
| 445 |
+
<div class="card">
|
| 446 |
+
<b>Detected GeoJSON bounds:</b><br>
|
| 447 |
+
minx={bounds[0]:.2f}, miny={bounds[1]:.2f}, maxx={bounds[2]:.2f}, maxy={bounds[3]:.2f}<br><br>
|
| 448 |
+
<b>Fix (fast):</b> Re-export your Kenya counties GeoJSON as <code>EPSG:4326 (WGS84)</code>.<br>
|
| 449 |
+
If using QGIS: <code>Right click layer → Export → Save Features As… → CRS: EPSG:4326</code><br>
|
| 450 |
+
Replace the file in your repo and redeploy.
|
| 451 |
+
</div>
|
| 452 |
+
""",
|
| 453 |
+
unsafe_allow_html=True,
|
| 454 |
+
)
|
| 455 |
+
st.stop()
|
| 456 |
+
|
| 457 |
months = sorted(hist["month"].dropna().unique())
|
| 458 |
selected_month = st.selectbox("Select Month", months, index=len(months) - 1)
|
| 459 |
|
|
|
|
| 464 |
)
|
| 465 |
|
| 466 |
data_month = hist[hist["month"] == selected_month].copy()
|
| 467 |
+
data_month["risk_proba"] = pd.to_numeric(data_month["risk_proba"], errors="coerce")
|
| 468 |
data_month["band"] = data_month["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 469 |
data_month["class"] = np.where(data_month["risk_proba"] >= threshold, "At Risk", "Secure")
|
| 470 |
data_month["county_norm"] = data_month["county"].map(normalize_county_name)
|
|
|
|
| 477 |
# Normalize GeoJSON join key
|
| 478 |
geojson_norm, featureidkey_norm = add_normalized_geojson_key(geojson)
|
| 479 |
|
|
|
|
| 480 |
geo_norm_set = {ft.get("properties", {}).get("__norm_county", "") for ft in geojson_norm.get("features", [])}
|
| 481 |
join_ok = data_month["county_norm"].isin(geo_norm_set).mean() if len(data_month) else 0.0
|
| 482 |
if join_ok < 0.98:
|
|
|
|
| 485 |
left, right = st.columns([2.2, 1.0], gap="large")
|
| 486 |
|
| 487 |
with left:
|
| 488 |
+
# DISCRETE COLORS: Secure green → Extreme red (as you requested)
|
| 489 |
fig = px.choropleth(
|
| 490 |
data_month.dropna(subset=["county_norm"]),
|
| 491 |
geojson=geojson_norm,
|
| 492 |
locations="county_norm",
|
| 493 |
featureidkey=featureidkey_norm,
|
| 494 |
+
color="band",
|
| 495 |
+
category_orders={"band": RISK_ORDER},
|
| 496 |
+
color_discrete_map=RISK_COLORS,
|
| 497 |
hover_name="county",
|
| 498 |
hover_data={"risk_proba": ":.3f", "band": True, "county_norm": False},
|
| 499 |
)
|
| 500 |
+
fig.update_traces(marker_line_width=1.0)
|
| 501 |
fig.update_geos(fitbounds="locations", visible=False)
|
| 502 |
+
fig.update_layout(height=620, margin=dict(l=10, r=10, t=10, b=10), legend_title_text="Risk Band")
|
| 503 |
st.plotly_chart(fig, use_container_width=True)
|
| 504 |
|
| 505 |
+
with st.expander("IPC Phase Classification Reference", expanded=False):
|
| 506 |
try:
|
| 507 |
st.dataframe(style_ipc_table(ipc_table), use_container_width=True, hide_index=True)
|
| 508 |
except TypeError:
|
| 509 |
st.dataframe(style_ipc_table(ipc_table), use_container_width=True)
|
| 510 |
|
| 511 |
with right:
|
| 512 |
+
st.markdown("#### Counties Sorted by Risk")
|
| 513 |
ranked = data_month.sort_values("risk_proba", ascending=False)[["county", "risk_proba"]].copy()
|
| 514 |
ranked["band"] = ranked["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 515 |
_, ranked_sty = styled_df_for_display(ranked, threshold)
|
|
|
|
| 542 |
st.error("No baseline row found for this county.")
|
| 543 |
st.stop()
|
| 544 |
|
|
|
|
| 545 |
for f in FEATURES:
|
| 546 |
if f not in base_row.columns:
|
| 547 |
base_row[f] = np.nan
|
|
|
|
| 557 |
def edit_feature(col, label, default_val, lo, hi, step):
|
| 558 |
if col not in x.columns:
|
| 559 |
return
|
|
|
|
| 560 |
dv = float(default_val) if pd.notna(default_val) else 0.0
|
|
|
|
|
|
|
| 561 |
lo2 = min(float(lo), dv)
|
| 562 |
hi2 = max(float(hi), dv)
|
|
|
|
| 563 |
val = st.number_input(
|
| 564 |
label,
|
| 565 |
value=float(dv),
|
|
|
|
| 601 |
color = RISK_COLORS.get(band, "#6b7280")
|
| 602 |
|
| 603 |
st.metric("Predicted Risk Probability (IPC Phase 3+)", f"{proba:.2f}")
|
|
|
|
| 604 |
st.markdown(
|
| 605 |
f"<div class='card'><b>Risk Band:</b> "
|
| 606 |
f"<span style='color:{color}; font-weight:800'>{band}</span></div>",
|
|
|
|
| 656 |
fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
|
| 657 |
st.plotly_chart(fig, use_container_width=True)
|
| 658 |
|
| 659 |
+
st.subheader("Historical Levels)")
|
| 660 |
tbl = county_data[["month", "risk_proba"]].copy()
|
| 661 |
tbl["band"] = tbl["risk_proba"].apply(lambda x: risk_band(x, threshold))
|
| 662 |
tbl = tbl.sort_values("month", ascending=False)
|
|
|
|
| 708 |
"""
|
| 709 |
)
|
| 710 |
|
| 711 |
+
st.subheader("IPC Phase Classification Reference")
|
| 712 |
try:
|
| 713 |
st.dataframe(style_ipc_table(ipc_table), use_container_width=True, hide_index=True)
|
| 714 |
except TypeError:
|