mcshoja commited on
Commit
e783d30
·
verified ·
1 Parent(s): 8d582ff

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +223 -143
src/streamlit_app.py CHANGED
@@ -62,6 +62,15 @@ def load_json(name: str):
62
  with open(p(name), "r", encoding="utf-8") as f:
63
  return json.load(f)
64
 
 
 
 
 
 
 
 
 
 
65
  # -------------------------------------------------------
66
  # STANDARDIZATION HELPERS
67
  # -------------------------------------------------------
@@ -118,6 +127,7 @@ def coerce_month(df: pd.DataFrame) -> pd.DataFrame:
118
  df = df.rename(columns={mcol: "month"})
119
  if "month" in df.columns:
120
  df["month"] = pd.to_datetime(df["month"], errors="coerce")
 
121
  return df
122
 
123
  def coerce_county(df: pd.DataFrame) -> pd.DataFrame:
@@ -190,12 +200,6 @@ def geojson_detect_county_prop(gj: dict) -> str:
190
 
191
  @st.cache_data
192
  def build_geo_ref(gj: dict) -> tuple[dict, pd.DataFrame]:
193
- """
194
- Adds:
195
- properties.__county_key (robust join key)
196
- properties.__county_name (display)
197
- Returns: (geojson, geo_ref_df[county_key, county])
198
- """
199
  prop = geojson_detect_county_prop(gj)
200
  rows = []
201
  for ft in gj.get("features", []):
@@ -211,7 +215,7 @@ def build_geo_ref(gj: dict) -> tuple[dict, pd.DataFrame]:
211
  return gj, ref
212
 
213
  # -------------------------------------------------------
214
- # RISK BANDS + IPC PHASE DISPLAY
215
  # -------------------------------------------------------
216
  RISK_COLORS = {
217
  "Secure": "#16a34a",
@@ -233,19 +237,15 @@ def risk_band(p: float, thr: float) -> str:
233
  return "High"
234
  return "Extreme"
235
 
236
- # IPC Phase mapping is display-only (because model predicts Phase 3+ risk).
237
- # This gives stakeholders a familiar frame:
238
- # Secure -> Phase 1-2 (below trigger), Watch/High/Extreme -> Phase 3+ (increasing severity)
239
- def ipc_phase_label(band: str) -> str:
240
- if band in ["Secure"]:
241
- return "IPC 1–2 (below trigger)"
242
- if band == "Watch":
243
- return "IPC 3+ (watch)"
244
- if band == "High":
245
- return "IPC 3+ (high)"
246
- if band == "Extreme":
247
- return "IPC 3+ (extreme)"
248
- return "Unknown"
249
 
250
  # -------------------------------------------------------
251
  # TABLE STYLING
@@ -255,15 +255,11 @@ def _hex_to_rgba(hex_color: str, alpha: float = 0.18) -> str:
255
  r = int(h[0:2], 16); g = int(h[2:4], 16); b = int(h[4:6], 16)
256
  return f"rgba({r},{g},{b},{alpha})"
257
 
258
- def style_table(df: pd.DataFrame) -> "pd.io.formats.style.Styler":
259
  d = df.copy()
260
  if "risk_proba" in d.columns:
261
  d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce")
262
 
263
- cols = [c for c in ["county", "risk_proba", "band", "ipc_phase"] if c in d.columns]
264
- if cols:
265
- d = d[cols]
266
-
267
  sty = d.style
268
  if "risk_proba" in d.columns:
269
  sty = sty.format({"risk_proba": "{:.3f}"})
@@ -275,6 +271,16 @@ def style_table(df: pd.DataFrame) -> "pd.io.formats.style.Styler":
275
  return f"background-color: {_hex_to_rgba(c, 0.22)}; font-weight:700;"
276
  sty = sty.applymap(band_cell, subset=["band"])
277
 
 
 
 
 
 
 
 
 
 
 
278
  sty = sty.set_properties(**{
279
  "border": "1px solid rgba(255,255,255,0.06)",
280
  "padding": "8px",
@@ -283,6 +289,10 @@ def style_table(df: pd.DataFrame) -> "pd.io.formats.style.Styler":
283
  }).set_table_styles([
284
  {"selector": "th", "props": [("font-weight", "700"), ("text-align", "left")]},
285
  ])
 
 
 
 
286
  return sty
287
 
288
  # -------------------------------------------------------
@@ -292,19 +302,14 @@ FRIENDLY_FEATURES = {
292
  "r3q_lag_1": "Rainfall anomaly (1-month lag)",
293
  "rain_lag_1": "Rainfall level (1-month lag)",
294
  "ndvi_lag_1": "Vegetation condition (NDVI, 1-month lag)",
295
- "vim_lag_1": "Vegetation condition (1-month lag)",
296
- "vim_lag_2": "Vegetation condition (2-month lag)",
297
- "vim_lag_3": "Vegetation condition (3-month lag)",
298
  "price_pct_change": "Food price change (%)",
299
  "price_lag_1": "Food price level (1-month lag)",
300
- "maize_price_per_kg": "Maize price (per kg)",
301
  "events_lag_1": "Conflict events (1-month lag)",
302
  "fatalities_lag_1": "Conflict fatalities (1-month lag)",
303
  "mpi": "Poverty index (MPI)",
304
  "is_ASAL": "ASAL county (1=yes, 0=no)",
305
  "prev_crisis_lag_1": "Previous month crisis (1=yes, 0=no)",
306
  }
307
-
308
  DRIVER_EXPLAIN = {
309
  "r3q_lag_1": "Rainfall shifts increase stress on crops, pasture, and water access.",
310
  "rain_lag_1": "Low rainfall reduces production and water availability.",
@@ -317,29 +322,29 @@ DRIVER_EXPLAIN = {
317
  "is_ASAL": "ASAL areas are more climate-sensitive and drought-prone.",
318
  "prev_crisis_lag_1": "Recent crisis often persists into the next month.",
319
  }
320
-
321
  def pretty_feature_name(f: str) -> str:
322
  return FRIENDLY_FEATURES.get(f, f)
323
-
324
  def driver_sentence(f: str) -> str:
325
  return DRIVER_EXPLAIN.get(f, "This factor is linked to changes in risk.")
326
 
327
  # -------------------------------------------------------
328
  # LOAD DATA
329
  # -------------------------------------------------------
330
- hist = load_csv("predictions_historical.csv")
331
- forecast = load_csv("predictions_forecast_next_month.csv")
332
- national = load_csv("national_trend.csv")
333
- baseline = load_csv("baseline_latest_features.csv")
334
  feature_importance = load_csv("feature_importance.csv")
335
  geojson = load_geo("kenya_counties.geojson")
336
  model = load_model("model.joblib")
337
  FEATURES = load_json("features.json")
338
 
339
- hist = coerce_month(coerce_risk(coerce_county(hist)))
340
- forecast = coerce_month(coerce_risk(coerce_county(forecast)))
341
- national = coerce_month(national)
342
- baseline = coerce_county(baseline)
 
 
343
 
344
  # national column coercion
345
  if "national_avg_risk" not in national.columns:
@@ -380,46 +385,60 @@ if "month" not in hist.columns or hist["month"].isna().all():
380
  latest_hist_month = hist["month"].max()
381
 
382
  # -------------------------------------------------------
383
- # ALWAYS return 47 counties (fixes blank map + missing counties)
384
- # This version NEVER assumes df has a "county" column after merge.
385
- # It always uses GEO_REF["county"] as the county name.
386
  # -------------------------------------------------------
387
  def ensure_all_47(df: pd.DataFrame, month: pd.Timestamp | None, thr: float) -> pd.DataFrame:
388
- base = GEO_REF.copy() # has columns: county_key, county
389
- d = df.copy()
390
 
 
 
 
 
 
391
  if "county_key" not in d.columns:
392
  if "county" in d.columns:
393
  d["county_key"] = d["county"].map(county_key)
394
  else:
395
  d["county_key"] = ""
396
 
397
- if month is not None and "month" in d.columns:
398
- d["month"] = pd.to_datetime(d["month"], errors="coerce")
399
- d = d[d["month"] == month].copy()
 
 
 
 
400
 
401
- # keep only what we need to merge (avoids suffix confusion)
402
- keep_cols = ["county_key"]
403
- if month is not None and "month" in d.columns:
404
- keep_cols.append("month")
405
  if "risk_proba" in d.columns:
406
- keep_cols.append("risk_proba")
407
- d = d[keep_cols].copy()
408
 
409
- # merge to base keeps all 47, county name always from GEO_REF
410
- on_cols = ["county_key"] + (["month"] if ("month" in d.columns and month is not None) else [])
411
  merged = base.merge(d, on=on_cols, how="left")
412
 
413
  merged["risk_proba"] = pd.to_numeric(merged.get("risk_proba", np.nan), errors="coerce")
414
  merged["band"] = merged["risk_proba"].apply(lambda x: risk_band(x, thr))
415
- merged["ipc_phase"] = merged["band"].apply(ipc_phase_label)
416
-
417
- # return canonical columns
418
- cols = ["county", "county_key"]
419
- if month is not None:
420
- cols.append("month")
421
- cols += ["risk_proba", "band", "ipc_phase"]
422
- return merged[cols]
 
 
 
 
 
 
 
 
 
423
 
424
  # -------------------------------------------------------
425
  # SIDEBAR
@@ -427,7 +446,6 @@ def ensure_all_47(df: pd.DataFrame, month: pd.Timestamp | None, thr: float) -> p
427
  st.sidebar.markdown("## System Controls")
428
  threshold = st.sidebar.slider("Risk Threshold", 0.10, 0.90, 0.45, 0.01)
429
 
430
- # ABOUT removed completely
431
  page = st.sidebar.radio(
432
  "Navigation",
433
  ["National Situation", "Risk Map", "Scenario Lab", "County Profile"],
@@ -449,11 +467,6 @@ if page == "National Situation":
449
 
450
  latest_data = hist[hist["month"] == latest_hist_month].copy()
451
  latest_data["band"] = latest_data["risk_proba"].apply(lambda x: risk_band(x, threshold))
452
- latest_data["ipc_phase"] = latest_data["band"].apply(ipc_phase_label)
453
-
454
- fc_data = forecast.copy()
455
- fc_data["band"] = fc_data["risk_proba"].apply(lambda x: risk_band(x, threshold))
456
- fc_data["ipc_phase"] = fc_data["band"].apply(ipc_phase_label)
457
 
458
  col1, col2, col3, col4 = st.columns(4)
459
  col1.metric("Observed Month (Latest)", latest_hist_month.strftime("%B %Y"))
@@ -465,8 +478,8 @@ if page == "National Situation":
465
  trend = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month")
466
  fig.add_trace(go.Scatter(x=trend["month"], y=trend["national_avg_risk"], mode="lines", name="Observed"))
467
 
468
- if not fc_data.empty:
469
- proj_y = float(fc_data["risk_proba"].mean())
470
  fig.add_trace(go.Scatter(x=[forecast_month], y=[proj_y], mode="markers", name="Projection"))
471
  if len(trend) > 0:
472
  fig.add_trace(go.Scatter(
@@ -481,17 +494,18 @@ if page == "National Situation":
481
  fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
482
  st.plotly_chart(fig, use_container_width=True)
483
 
484
- st.subheader("Top Counties Above Threshold")
485
  top_risk = (
486
  latest_data[latest_data["risk_proba"] >= threshold]
487
  .sort_values("risk_proba", ascending=False)
488
- .head(20)[["county", "risk_proba", "band", "ipc_phase"]]
489
  .copy()
490
  )
491
  if top_risk.empty:
492
  st.info("No counties are above the current threshold in the latest observed month.")
493
  else:
494
- st.dataframe(style_table(top_risk), use_container_width=True, hide_index=True)
 
495
 
496
  # =======================================================
497
  # RISK MAP
@@ -505,68 +519,124 @@ elif page == "Risk Map":
505
  if view == "Historical":
506
  months = sorted(hist["month"].dropna().unique())
507
  selected_month = st.selectbox("Month", months, index=len(months) - 1)
508
- display_month = pd.to_datetime(selected_month)
509
- df_full = ensure_all_47(hist, display_month, threshold)
510
  else:
511
- display_month = forecast_month
512
- if "month" in forecast.columns and not forecast["month"].isna().all():
513
- df_full = ensure_all_47(forecast, forecast["month"].max(), threshold)
514
- else:
515
- df_full = ensure_all_47(forecast, None, threshold)
 
 
516
 
517
  st.markdown(f"**Displaying:** {display_month.strftime('%B %Y')}")
518
 
519
- # filtered list
520
- if filt == "At Risk (>= threshold)":
521
- df_list = df_full[df_full["risk_proba"] >= threshold].copy()
522
- elif filt == "Secure (< threshold)":
523
- df_list = df_full[df_full["risk_proba"] < threshold].copy()
524
  else:
525
- df_list = df_full.copy()
526
-
527
- # map: always show all 47, fade non-matching to Unknown when filtered
528
- df_map = df_full.copy()
529
- if filt != "All":
530
- keep = set(df_list["county_key"].tolist())
531
- df_map.loc[~df_map["county_key"].isin(keep), "band"] = "Unknown"
532
- df_map.loc[~df_map["county_key"].isin(keep), "ipc_phase"] = "Unknown"
533
-
534
- left, right = st.columns([2.2, 1.0], gap="large")
535
-
536
- with left:
537
- fig = px.choropleth_mapbox(
538
- df_map,
539
- geojson=geojson,
540
- locations="county_key",
541
- featureidkey="properties.__county_key",
542
- color="band",
543
- category_orders={"band": RISK_ORDER},
544
- color_discrete_map=RISK_COLORS,
545
- hover_name="county",
546
- hover_data={"risk_proba": ":.3f", "ipc_phase": True},
547
- mapbox_style="carto-positron",
548
- zoom=5.2,
549
- center={"lat": 0.2, "lon": 37.8},
550
- height=650,
551
- opacity=0.85,
552
- )
553
- fig.update_layout(showlegend=False, margin=dict(l=10, r=10, t=10, b=10))
554
- fig.update_traces(marker_line_width=0.9)
555
- st.plotly_chart(fig, use_container_width=True)
556
-
557
- # Small, relevant IPC note under the map (no full definition here)
558
- st.markdown(
559
- "<div class='small-note'>IPC shown here is a display frame aligned to the Phase 3+ risk trigger.</div>",
560
- unsafe_allow_html=True
561
- )
562
-
563
- with right:
564
- st.subheader("Counties Sorted by Risk")
565
- ranked = df_list.sort_values("risk_proba", ascending=False)[["county", "risk_proba", "band", "ipc_phase"]].copy()
566
- if ranked.empty:
567
- st.info("No counties match this filter under the current threshold.")
568
  else:
569
- st.dataframe(style_table(ranked), use_container_width=True, height=650, hide_index=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570
 
571
  # =======================================================
572
  # SCENARIO LAB
@@ -599,29 +669,29 @@ elif page == "Scenario Lab":
599
  with c1:
600
  if "r3q_lag_1" in x_edit.columns:
601
  x_edit["r3q_lag_1"] = st.number_input(
602
- FRIENDLY_FEATURES.get("r3q_lag_1", "r3q_lag_1"),
603
  value=float(x_edit["r3q_lag_1"].iloc[0]) if pd.notna(x_edit["r3q_lag_1"].iloc[0]) else 0.0
604
  )
605
  if "ndvi_lag_1" in x_edit.columns:
606
  x_edit["ndvi_lag_1"] = st.number_input(
607
- FRIENDLY_FEATURES.get("ndvi_lag_1", "ndvi_lag_1"),
608
  value=float(x_edit["ndvi_lag_1"].iloc[0]) if pd.notna(x_edit["ndvi_lag_1"].iloc[0]) else 0.0
609
  )
610
  with c2:
611
  if "price_pct_change" in x_edit.columns:
612
  x_edit["price_pct_change"] = st.number_input(
613
- FRIENDLY_FEATURES.get("price_pct_change", "price_pct_change"),
614
  value=float(x_edit["price_pct_change"].iloc[0]) if pd.notna(x_edit["price_pct_change"].iloc[0]) else 0.0
615
  )
616
  if "events_lag_1" in x_edit.columns:
617
  x_edit["events_lag_1"] = st.number_input(
618
- FRIENDLY_FEATURES.get("events_lag_1", "events_lag_1"),
619
  value=float(x_edit["events_lag_1"].iloc[0]) if pd.notna(x_edit["events_lag_1"].iloc[0]) else 0.0
620
  )
621
 
622
  with st.expander("Advanced inputs"):
623
  for f in FEATURES:
624
- label = FRIENDLY_FEATURES.get(f, f)
625
  cur = x_edit[f].iloc[0]
626
  val = st.number_input(label, value=float(cur) if pd.notna(cur) else 0.0, key=f"adv_{county}_{f}")
627
  x_edit[f] = val
@@ -633,13 +703,13 @@ elif page == "Scenario Lab":
633
  delta = new_prob - base_prob
634
 
635
  b1, b2, b3 = st.columns(3)
636
- b1.metric("Baseline Probability", f"{base_prob:.4f}")
637
- b2.metric("Scenario Probability", f"{new_prob:.4f}")
638
  b3.metric("Change (Δ)", f"{delta:.4f}")
639
 
640
  band = risk_band(new_prob, threshold)
641
  st.markdown(f"**Risk Band:** {band}")
642
- st.markdown(f"**IPC framing:** {ipc_phase_label(band)}")
643
  except Exception as e:
644
  st.error(f"Prediction failed (model/features mismatch): {e}")
645
 
@@ -679,10 +749,20 @@ elif page == "County Profile":
679
  latest_obs = float(hist_c["risk_proba"].iloc[-1]) if not hist_c.empty else np.nan
680
  band = risk_band(latest_obs, threshold) if np.isfinite(latest_obs) else "Unknown"
681
 
682
- c1, c2, c3 = st.columns(3)
683
- c1.metric("Latest Observed Risk", f"{latest_obs:.2f}" if np.isfinite(latest_obs) else "N/A")
684
  c2.metric("Observed Month (Latest)", hist_c["month"].iloc[-1].strftime("%B %Y") if not hist_c.empty else "N/A")
685
- c3.metric("IPC framing", ipc_phase_label(band) if band != "Unknown" else "Unknown")
 
 
 
 
 
 
 
 
 
 
686
 
687
  st.subheader("Key Drivers")
688
  if "feature" in feature_importance.columns and "importance" in feature_importance.columns:
@@ -693,6 +773,6 @@ elif page == "County Profile":
693
  )
694
  for _, r in top_drivers.iterrows():
695
  f = str(r["feature"])
696
- st.markdown(f"- **{FRIENDLY_FEATURES.get(f, f)}** — {driver_sentence(f)}")
697
  else:
698
  st.info("feature_importance.csv is missing expected columns (feature, importance).")
 
62
  with open(p(name), "r", encoding="utf-8") as f:
63
  return json.load(f)
64
 
65
+ def load_optional_csv(filename: str) -> pd.DataFrame | None:
66
+ fp = p(filename)
67
+ if fp.exists():
68
+ try:
69
+ return pd.read_csv(fp)
70
+ except Exception:
71
+ return None
72
+ return None
73
+
74
  # -------------------------------------------------------
75
  # STANDARDIZATION HELPERS
76
  # -------------------------------------------------------
 
127
  df = df.rename(columns={mcol: "month"})
128
  if "month" in df.columns:
129
  df["month"] = pd.to_datetime(df["month"], errors="coerce")
130
+ df["month"] = df["month"].dt.to_period("M").dt.to_timestamp() # force month-start
131
  return df
132
 
133
  def coerce_county(df: pd.DataFrame) -> pd.DataFrame:
 
200
 
201
  @st.cache_data
202
  def build_geo_ref(gj: dict) -> tuple[dict, pd.DataFrame]:
 
 
 
 
 
 
203
  prop = geojson_detect_county_prop(gj)
204
  rows = []
205
  for ft in gj.get("features", []):
 
215
  return gj, ref
216
 
217
  # -------------------------------------------------------
218
+ # RISK + IPC
219
  # -------------------------------------------------------
220
  RISK_COLORS = {
221
  "Secure": "#16a34a",
 
237
  return "High"
238
  return "Extreme"
239
 
240
+ # Observed IPC Phase colors (1–5)
241
+ IPC_COLORS = {
242
+ 1: "#16a34a",
243
+ 2: "#84cc16",
244
+ 3: "#facc15",
245
+ 4: "#f97316",
246
+ 5: "#dc2626",
247
+ }
248
+ IPC_ORDER = [1, 2, 3, 4, 5]
 
 
 
 
249
 
250
  # -------------------------------------------------------
251
  # TABLE STYLING
 
255
  r = int(h[0:2], 16); g = int(h[2:4], 16); b = int(h[4:6], 16)
256
  return f"rgba({r},{g},{b},{alpha})"
257
 
258
+ def style_risk_table(df: pd.DataFrame) -> "pd.io.formats.style.Styler":
259
  d = df.copy()
260
  if "risk_proba" in d.columns:
261
  d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce")
262
 
 
 
 
 
263
  sty = d.style
264
  if "risk_proba" in d.columns:
265
  sty = sty.format({"risk_proba": "{:.3f}"})
 
271
  return f"background-color: {_hex_to_rgba(c, 0.22)}; font-weight:700;"
272
  sty = sty.applymap(band_cell, subset=["band"])
273
 
274
+ if "ipc_phase" in d.columns:
275
+ def phase_cell(v):
276
+ try:
277
+ vv = int(v)
278
+ c = IPC_COLORS.get(vv, "#6b7280")
279
+ return f"background-color: {_hex_to_rgba(c, 0.22)}; font-weight:700;"
280
+ except Exception:
281
+ return ""
282
+ sty = sty.applymap(phase_cell, subset=["ipc_phase"])
283
+
284
  sty = sty.set_properties(**{
285
  "border": "1px solid rgba(255,255,255,0.06)",
286
  "padding": "8px",
 
289
  }).set_table_styles([
290
  {"selector": "th", "props": [("font-weight", "700"), ("text-align", "left")]},
291
  ])
292
+ try:
293
+ sty = sty.hide(axis="index")
294
+ except Exception:
295
+ pass
296
  return sty
297
 
298
  # -------------------------------------------------------
 
302
  "r3q_lag_1": "Rainfall anomaly (1-month lag)",
303
  "rain_lag_1": "Rainfall level (1-month lag)",
304
  "ndvi_lag_1": "Vegetation condition (NDVI, 1-month lag)",
 
 
 
305
  "price_pct_change": "Food price change (%)",
306
  "price_lag_1": "Food price level (1-month lag)",
 
307
  "events_lag_1": "Conflict events (1-month lag)",
308
  "fatalities_lag_1": "Conflict fatalities (1-month lag)",
309
  "mpi": "Poverty index (MPI)",
310
  "is_ASAL": "ASAL county (1=yes, 0=no)",
311
  "prev_crisis_lag_1": "Previous month crisis (1=yes, 0=no)",
312
  }
 
313
  DRIVER_EXPLAIN = {
314
  "r3q_lag_1": "Rainfall shifts increase stress on crops, pasture, and water access.",
315
  "rain_lag_1": "Low rainfall reduces production and water availability.",
 
322
  "is_ASAL": "ASAL areas are more climate-sensitive and drought-prone.",
323
  "prev_crisis_lag_1": "Recent crisis often persists into the next month.",
324
  }
 
325
  def pretty_feature_name(f: str) -> str:
326
  return FRIENDLY_FEATURES.get(f, f)
 
327
  def driver_sentence(f: str) -> str:
328
  return DRIVER_EXPLAIN.get(f, "This factor is linked to changes in risk.")
329
 
330
  # -------------------------------------------------------
331
  # LOAD DATA
332
  # -------------------------------------------------------
333
+ hist = coerce_month(coerce_risk(coerce_county(load_csv("predictions_historical.csv"))))
334
+ forecast = coerce_month(coerce_risk(coerce_county(load_csv("predictions_forecast_next_month.csv"))))
335
+ national = coerce_month(load_csv("national_trend.csv"))
336
+ baseline = coerce_county(load_csv("baseline_latest_features.csv"))
337
  feature_importance = load_csv("feature_importance.csv")
338
  geojson = load_geo("kenya_counties.geojson")
339
  model = load_model("model.joblib")
340
  FEATURES = load_json("features.json")
341
 
342
+ # OPTIONAL observed IPC file (for exact phase display on historical maps)
343
+ ipc_obs = load_optional_csv("ipc_phases_county_month.csv")
344
+ if ipc_obs is not None:
345
+ ipc_obs = coerce_month(coerce_county(ipc_obs))
346
+ if "ipc_phase" in ipc_obs.columns:
347
+ ipc_obs["ipc_phase"] = pd.to_numeric(ipc_obs["ipc_phase"], errors="coerce").astype("Int64")
348
 
349
  # national column coercion
350
  if "national_avg_risk" not in national.columns:
 
385
  latest_hist_month = hist["month"].max()
386
 
387
  # -------------------------------------------------------
388
+ # FIXED: ALWAYS return 47 counties (no month KeyError)
 
 
389
  # -------------------------------------------------------
390
  def ensure_all_47(df: pd.DataFrame, month: pd.Timestamp | None, thr: float) -> pd.DataFrame:
391
+ base = GEO_REF.copy() # county_key, county
 
392
 
393
+ # If a specific month is requested, add it to base (THIS fixes your KeyError: 'month')
394
+ if month is not None:
395
+ base["month"] = pd.to_datetime(month).to_period("M").to_timestamp()
396
+
397
+ d = df.copy()
398
  if "county_key" not in d.columns:
399
  if "county" in d.columns:
400
  d["county_key"] = d["county"].map(county_key)
401
  else:
402
  d["county_key"] = ""
403
 
404
+ # If month is requested, make sure d has a month column, then filter
405
+ if month is not None:
406
+ if "month" not in d.columns:
407
+ d["month"] = pd.to_datetime(month).to_period("M").to_timestamp()
408
+ else:
409
+ d["month"] = pd.to_datetime(d["month"], errors="coerce").dt.to_period("M").dt.to_timestamp()
410
+ d = d[d["month"] == base["month"].iloc[0]].copy()
411
 
412
+ # minimal merge columns
413
+ keep = ["county_key"]
414
+ if month is not None:
415
+ keep.append("month")
416
  if "risk_proba" in d.columns:
417
+ keep.append("risk_proba")
418
+ d = d[keep].copy()
419
 
420
+ on_cols = ["county_key"] + (["month"] if month is not None else [])
 
421
  merged = base.merge(d, on=on_cols, how="left")
422
 
423
  merged["risk_proba"] = pd.to_numeric(merged.get("risk_proba", np.nan), errors="coerce")
424
  merged["band"] = merged["risk_proba"].apply(lambda x: risk_band(x, thr))
425
+ return merged
426
+
427
+ def attach_observed_ipc(df47: pd.DataFrame, month: pd.Timestamp) -> pd.DataFrame:
428
+ if ipc_obs is None:
429
+ df47["ipc_phase"] = pd.NA
430
+ return df47
431
+ m = pd.to_datetime(month).to_period("M").to_timestamp()
432
+ tmp = ipc_obs.copy()
433
+ if "month" not in tmp.columns:
434
+ df47["ipc_phase"] = pd.NA
435
+ return df47
436
+ tmp = tmp[tmp["month"] == m]
437
+ if tmp.empty or "ipc_phase" not in tmp.columns:
438
+ df47["ipc_phase"] = pd.NA
439
+ return df47
440
+ out = df47.merge(tmp[["county_key", "ipc_phase"]], on="county_key", how="left")
441
+ return out
442
 
443
  # -------------------------------------------------------
444
  # SIDEBAR
 
446
  st.sidebar.markdown("## System Controls")
447
  threshold = st.sidebar.slider("Risk Threshold", 0.10, 0.90, 0.45, 0.01)
448
 
 
449
  page = st.sidebar.radio(
450
  "Navigation",
451
  ["National Situation", "Risk Map", "Scenario Lab", "County Profile"],
 
467
 
468
  latest_data = hist[hist["month"] == latest_hist_month].copy()
469
  latest_data["band"] = latest_data["risk_proba"].apply(lambda x: risk_band(x, threshold))
 
 
 
 
 
470
 
471
  col1, col2, col3, col4 = st.columns(4)
472
  col1.metric("Observed Month (Latest)", latest_hist_month.strftime("%B %Y"))
 
478
  trend = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month")
479
  fig.add_trace(go.Scatter(x=trend["month"], y=trend["national_avg_risk"], mode="lines", name="Observed"))
480
 
481
+ if not forecast.empty and "risk_proba" in forecast.columns:
482
+ proj_y = float(forecast["risk_proba"].mean())
483
  fig.add_trace(go.Scatter(x=[forecast_month], y=[proj_y], mode="markers", name="Projection"))
484
  if len(trend) > 0:
485
  fig.add_trace(go.Scatter(
 
494
  fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
495
  st.plotly_chart(fig, use_container_width=True)
496
 
497
+ st.subheader("Top Counties Above Threshold (Predicted IPC 3+ Risk)")
498
  top_risk = (
499
  latest_data[latest_data["risk_proba"] >= threshold]
500
  .sort_values("risk_proba", ascending=False)
501
+ .head(20)[["county", "risk_proba"]]
502
  .copy()
503
  )
504
  if top_risk.empty:
505
  st.info("No counties are above the current threshold in the latest observed month.")
506
  else:
507
+ top_risk["band"] = top_risk["risk_proba"].apply(lambda x: risk_band(x, threshold))
508
+ st.dataframe(style_risk_table(top_risk), use_container_width=True)
509
 
510
  # =======================================================
511
  # RISK MAP
 
519
  if view == "Historical":
520
  months = sorted(hist["month"].dropna().unique())
521
  selected_month = st.selectbox("Month", months, index=len(months) - 1)
522
+ display_month = pd.to_datetime(selected_month).to_period("M").to_timestamp()
 
523
  else:
524
+ display_month = forecast_month.to_period("M").to_timestamp()
525
+
526
+ # Layer: predicted risk always available; observed IPC only if file exists and view==Historical
527
+ layer_options = ["Predicted IPC 3+ Risk"]
528
+ if (ipc_obs is not None) and (view == "Historical"):
529
+ layer_options.append("Observed IPC Phase (1–5)")
530
+ layer = st.radio("Map Layer", layer_options, horizontal=True)
531
 
532
  st.markdown(f"**Displaying:** {display_month.strftime('%B %Y')}")
533
 
534
+ # Build the 47-county frame for the chosen view/month
535
+ if view == "Historical":
536
+ df47 = ensure_all_47(hist, display_month, threshold)
 
 
537
  else:
538
+ # forecast may have no month col, we still want 47 counties
539
+ if "month" in forecast.columns and not forecast["month"].isna().all():
540
+ df47 = ensure_all_47(forecast, forecast["month"].max(), threshold)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
541
  else:
542
+ df47 = ensure_all_47(forecast, None, threshold)
543
+
544
+ # Attach observed phase if requested
545
+ if layer == "Observed IPC Phase (1–5)":
546
+ df47 = attach_observed_ipc(df47, display_month)
547
+
548
+ # Filter affects the LIST; map still shows all 47 (fade others)
549
+ if layer == "Predicted IPC 3+ Risk":
550
+ if filt == "At Risk (>= threshold)":
551
+ df_list = df47[df47["risk_proba"] >= threshold].copy()
552
+ elif filt == "Secure (< threshold)":
553
+ df_list = df47[df47["risk_proba"] < threshold].copy()
554
+ else:
555
+ df_list = df47.copy()
556
+
557
+ df_map = df47.copy()
558
+ if filt != "All":
559
+ keep = set(df_list["county_key"].tolist())
560
+ df_map.loc[~df_map["county_key"].isin(keep), "band"] = "Unknown"
561
+
562
+ left, right = st.columns([2.2, 1.0], gap="large")
563
+
564
+ with left:
565
+ fig = px.choropleth_mapbox(
566
+ df_map,
567
+ geojson=geojson,
568
+ locations="county_key",
569
+ featureidkey="properties.__county_key",
570
+ color="band",
571
+ category_orders={"band": RISK_ORDER},
572
+ color_discrete_map=RISK_COLORS,
573
+ hover_name="county",
574
+ hover_data={"risk_proba": ":.3f"},
575
+ mapbox_style="carto-positron",
576
+ zoom=5.2,
577
+ center={"lat": 0.2, "lon": 37.8},
578
+ height=650,
579
+ opacity=0.85,
580
+ )
581
+ fig.update_layout(showlegend=False, margin=dict(l=10, r=10, t=10, b=10))
582
+ fig.update_traces(marker_line_width=0.9)
583
+ st.plotly_chart(fig, use_container_width=True)
584
+
585
+ with right:
586
+ st.subheader("Counties Sorted by Risk")
587
+ ranked = df_list.sort_values("risk_proba", ascending=False)[["county", "risk_proba"]].copy()
588
+ ranked["band"] = ranked["risk_proba"].apply(lambda x: risk_band(x, threshold))
589
+ st.dataframe(style_risk_table(ranked), use_container_width=True, height=650)
590
+
591
+ else:
592
+ # Observed IPC Phase map + list (exact phases, historical only)
593
+ df_list = df47.copy()
594
+ if filt != "All":
595
+ # For observed IPC, "at risk" means phase >=3, "secure" means phase <=2
596
+ if filt == "At Risk (>= threshold)":
597
+ df_list = df_list[df_list["ipc_phase"].fillna(0).astype(int) >= 3].copy()
598
+ else:
599
+ df_list = df_list[df_list["ipc_phase"].fillna(0).astype(int) <= 2].copy()
600
+
601
+ df_map = df47.copy()
602
+ if filt != "All":
603
+ keep = set(df_list["county_key"].tolist())
604
+ df_map.loc[~df_map["county_key"].isin(keep), "ipc_phase"] = pd.NA
605
+
606
+ left, right = st.columns([2.2, 1.0], gap="large")
607
+
608
+ with left:
609
+ # For NA phases, plot as 0 -> grey using a helper column
610
+ df_map["_phase_plot"] = df_map["ipc_phase"].fillna(0).astype(int)
611
+ phase_colors = {0: "#6b7280", **IPC_COLORS}
612
+
613
+ fig = px.choropleth_mapbox(
614
+ df_map,
615
+ geojson=geojson,
616
+ locations="county_key",
617
+ featureidkey="properties.__county_key",
618
+ color="_phase_plot",
619
+ category_orders={"_phase_plot": [0, 1, 2, 3, 4, 5]},
620
+ color_discrete_map=phase_colors,
621
+ hover_name="county",
622
+ hover_data={"ipc_phase": True},
623
+ mapbox_style="carto-positron",
624
+ zoom=5.2,
625
+ center={"lat": 0.2, "lon": 37.8},
626
+ height=650,
627
+ opacity=0.85,
628
+ )
629
+ fig.update_layout(showlegend=False, margin=dict(l=10, r=10, t=10, b=10))
630
+ fig.update_traces(marker_line_width=0.9)
631
+ st.plotly_chart(fig, use_container_width=True)
632
+
633
+ with right:
634
+ st.subheader("Counties by Observed IPC Phase")
635
+ ranked = df_list.copy()
636
+ ranked = ranked[["county", "ipc_phase"]].copy()
637
+ ranked["ipc_phase"] = ranked["ipc_phase"].astype("Int64")
638
+ ranked = ranked.sort_values(["ipc_phase", "county"], ascending=[False, True])
639
+ st.dataframe(style_risk_table(ranked), use_container_width=True, height=650)
640
 
641
  # =======================================================
642
  # SCENARIO LAB
 
669
  with c1:
670
  if "r3q_lag_1" in x_edit.columns:
671
  x_edit["r3q_lag_1"] = st.number_input(
672
+ pretty_feature_name("r3q_lag_1"),
673
  value=float(x_edit["r3q_lag_1"].iloc[0]) if pd.notna(x_edit["r3q_lag_1"].iloc[0]) else 0.0
674
  )
675
  if "ndvi_lag_1" in x_edit.columns:
676
  x_edit["ndvi_lag_1"] = st.number_input(
677
+ pretty_feature_name("ndvi_lag_1"),
678
  value=float(x_edit["ndvi_lag_1"].iloc[0]) if pd.notna(x_edit["ndvi_lag_1"].iloc[0]) else 0.0
679
  )
680
  with c2:
681
  if "price_pct_change" in x_edit.columns:
682
  x_edit["price_pct_change"] = st.number_input(
683
+ pretty_feature_name("price_pct_change"),
684
  value=float(x_edit["price_pct_change"].iloc[0]) if pd.notna(x_edit["price_pct_change"].iloc[0]) else 0.0
685
  )
686
  if "events_lag_1" in x_edit.columns:
687
  x_edit["events_lag_1"] = st.number_input(
688
+ pretty_feature_name("events_lag_1"),
689
  value=float(x_edit["events_lag_1"].iloc[0]) if pd.notna(x_edit["events_lag_1"].iloc[0]) else 0.0
690
  )
691
 
692
  with st.expander("Advanced inputs"):
693
  for f in FEATURES:
694
+ label = pretty_feature_name(f)
695
  cur = x_edit[f].iloc[0]
696
  val = st.number_input(label, value=float(cur) if pd.notna(cur) else 0.0, key=f"adv_{county}_{f}")
697
  x_edit[f] = val
 
703
  delta = new_prob - base_prob
704
 
705
  b1, b2, b3 = st.columns(3)
706
+ b1.metric("Baseline Probability (Phase 3+)", f"{base_prob:.4f}")
707
+ b2.metric("Scenario Probability (Phase 3+)", f"{new_prob:.4f}")
708
  b3.metric("Change (Δ)", f"{delta:.4f}")
709
 
710
  band = risk_band(new_prob, threshold)
711
  st.markdown(f"**Risk Band:** {band}")
712
+ st.markdown("<div class='small-note'>This model predicts the probability of IPC Phase 3+ (not exact phases 1–5).</div>", unsafe_allow_html=True)
713
  except Exception as e:
714
  st.error(f"Prediction failed (model/features mismatch): {e}")
715
 
 
749
  latest_obs = float(hist_c["risk_proba"].iloc[-1]) if not hist_c.empty else np.nan
750
  band = risk_band(latest_obs, threshold) if np.isfinite(latest_obs) else "Unknown"
751
 
752
+ c1, c2 = st.columns(2)
753
+ c1.metric("Latest Observed Risk (Phase 3+ Probability)", f"{latest_obs:.2f}" if np.isfinite(latest_obs) else "N/A")
754
  c2.metric("Observed Month (Latest)", hist_c["month"].iloc[-1].strftime("%B %Y") if not hist_c.empty else "N/A")
755
+
756
+ # Observed exact phase (if dataset provided)
757
+ if ipc_obs is not None:
758
+ m = hist_c["month"].iloc[-1] if not hist_c.empty else None
759
+ if m is not None:
760
+ obs_phase = (
761
+ ipc_obs[(ipc_obs["county"] == county) & (ipc_obs["month"] == m)]
762
+ .get("ipc_phase")
763
+ )
764
+ if obs_phase is not None and len(obs_phase) > 0 and pd.notna(obs_phase.iloc[0]):
765
+ st.metric("Observed IPC Phase (Exact)", int(obs_phase.iloc[0]))
766
 
767
  st.subheader("Key Drivers")
768
  if "feature" in feature_importance.columns and "importance" in feature_importance.columns:
 
773
  )
774
  for _, r in top_drivers.iterrows():
775
  f = str(r["feature"])
776
+ st.markdown(f"- **{pretty_feature_name(f)}** — {driver_sentence(f)}")
777
  else:
778
  st.info("feature_importance.csv is missing expected columns (feature, importance).")