"""
ARIA — Aide à la Recommandation d'Irrigation Agricole
Burkina Faso · Machine Learning · DataBuilder Africa · 2026
"""
import os, warnings, joblib
import numpy as np
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
warnings.filterwarnings("ignore")
# ── Constantes ────────────────────────────────────────────────────────────────
REGIONS = {
0:"Boucle du Mouhoun", 1:"Cascades", 2:"Centre",
3:"Centre-Est", 4:"Centre-Nord", 5:"Centre-Ouest",
6:"Centre-Sud", 7:"Est", 8:"Hauts-Bassins",
9:"Nord", 10:"Plateau Central",11:"Sahel",
12:"Sud-Ouest",
}
CROPS = {0:"Coton", 1:"Maïs", 2:"Sorgho", 3:"Mil"}
SOIL_TYPES = {0:"Sableux", 1:"Limoneux", 2:"Argileux"}
SEASONS = {1:"Saison sèche (déc–mars)", 2:"Pré-hivernage (avr–mai)",
3:"Hivernage / pluies (juin–sept)", 4:"Post-hivernage (oct–nov)"}
# Coordonnées approx. des capitales régionales du Burkina Faso
REGION_COORDS = {
"Boucle du Mouhoun": (12.36, -3.30),
"Cascades": (10.59, -4.30),
"Centre": (12.37, -1.53),
"Centre-Est": (11.88, -0.37),
"Centre-Nord": (13.17, -1.07),
"Centre-Ouest": (11.88, -2.36),
"Centre-Sud": (11.40, -1.07),
"Est": (12.37, 0.35),
"Hauts-Bassins": (11.18, -4.30),
"Nord": (13.61, -2.20),
"Plateau Central": (12.60, -0.86),
"Sahel": (14.00, -0.05),
"Sud-Ouest": (10.60, -3.25),
}
CROP_FACTORS = {0:0.8, 1:0.6, 2:0.5, 3:0.4}
CROP_COLORS = {0:"#8B4513", 1:"#DAA520", 2:"#228B22", 3:"#32CD32"}
CROP_DESC = {0:"Grande culture d'export, très exigeante en eau",
1:"Céréale alimentaire de base, sensible au stress",
2:"Céréale résistante, adaptée aux zones semi-arides",
3:"Céréale sahélienne, très économe en eau"}
SOIL_DESC = {0:"Draine rapidement, irrigations fréquentes et modérées",
1:"Équilibre idéal rétention/drainage pour toutes cultures",
2:"Retient longtemps l'eau, surveiller la saturation"}
REGION_COLORS = ["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd",
"#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf",
"#aec7e8","#ffbb78","#98df8a"]
MODEL_CACHE = "models_cache.pkl"
DATA_FILE = "dataset_burkina_irrigation.csv"
FEATURES_RAW = [
"soil_moisture","temperature","rainfall","irrigated_area",
"region","fertilizer_kg","days_since_irrigation",
"soil_moisture_sq","days_irrigation_sq",
"temp_rain_ratio","et0_soil_interaction",
]
# ── Page config ───────────────────────────────────────────────────────────────
st.set_page_config(
page_title="ARIA — Irrigation Burkina Faso",
page_icon="🌾",
layout="wide",
initial_sidebar_state="expanded",
)
# ── CSS ───────────────────────────────────────────────────────────────────────
st.markdown("""
""", unsafe_allow_html=True)
# ── Feature engineering ───────────────────────────────────────────────────────
def build_features(df: pd.DataFrame) -> pd.DataFrame:
d = df.copy()
d["soil_moisture_sq"] = d["soil_moisture"] ** 2
d["days_irrigation_sq"] = d["days_since_irrigation"] ** 2
d["temp_rain_ratio"] = d["temperature"] / (d["rainfall"] + 0.1)
et0 = d.get("ET0_mm_day", pd.Series(np.maximum(0, (d["temperature"]-20)*0.1), index=d.index))
d["et0_soil_interaction"] = et0 * (1 - d["soil_moisture"] / 100)
d = pd.get_dummies(d, columns=["crop_type","season","soil_type"],
prefix=["crop","season","soil"], drop_first=False)
return d
def get_feature_cols(df: pd.DataFrame) -> list:
ohe = [c for c in df.columns
if c.startswith(("crop_","season_","soil_"))
and df[c].dtype in (np.dtype("bool"), np.dtype("uint8"))
and c not in FEATURES_RAW]
return FEATURES_RAW + ohe
# ── Entraînement / chargement ─────────────────────────────────────────────────
@st.cache_resource(show_spinner=False)
def load_or_train_models():
if os.path.exists(MODEL_CACHE):
return joblib.load(MODEL_CACHE)
if not os.path.exists(DATA_FILE):
return None
df_raw = pd.read_csv(DATA_FILE)
df = build_features(df_raw)
FEATS = get_feature_cols(df)
X = df[FEATS].values
y_irr = df["irrigation_need_mm"].values
y_yield = df["yield_predicted_tonnes_ha"].values
y_water = df["water_efficiency"].values
X_train, X_test, yi_tr, yi_te = train_test_split(X, y_irr, test_size=0.20, random_state=42)
_, _, yy_tr, yy_te = train_test_split(X, y_yield, test_size=0.20, random_state=42)
_, _, yw_tr, yw_te = train_test_split(X, y_water, test_size=0.20, random_state=42)
scaler = StandardScaler()
X_train_sc = scaler.fit_transform(X_train)
X_test_sc = scaler.transform(X_test)
rf = RandomForestRegressor(n_estimators=200, max_depth=15, min_samples_split=5,
min_samples_leaf=2, n_jobs=-1, random_state=42)
rf.fit(X_train, yi_tr)
gb = GradientBoostingRegressor(n_estimators=300, learning_rate=0.05, max_depth=4,
min_samples_split=5, subsample=0.7, random_state=42)
gb.fit(X_train, yy_tr)
nn = MLPRegressor(hidden_layer_sizes=(64,32), activation='relu', solver='adam',
alpha=0.001, learning_rate_init=0.0005, max_iter=1000,
early_stopping=True, n_iter_no_change=50, random_state=42)
nn.fit(X_train_sc, yw_tr)
def metrics(y_true, y_pred):
return {"R2": round(r2_score(y_true, y_pred), 4),
"RMSE": round(np.sqrt(mean_squared_error(y_true, y_pred)), 5),
"MAE": round(mean_absolute_error(y_true, y_pred), 5)}
perf = {"RF": metrics(yi_te, rf.predict(X_test)),
"GB": metrics(yy_te, gb.predict(X_test)),
"NN": metrics(yw_te, nn.predict(X_test_sc))}
bundle = {"rf":rf,"gb":gb,"nn":nn,"scaler":scaler,"features":FEATS,"perf":perf}
joblib.dump(bundle, MODEL_CACHE)
return bundle
@st.cache_data(show_spinner=False)
def load_data():
if os.path.exists(DATA_FILE):
return pd.read_csv(DATA_FILE)
return None
def predict(bundle, soil_moisture, temperature, rainfall, crop_type,
irrigated_area, season, region, soil_type, fertilizer_kg, days):
rf, gb, nn, scaler, FEATS = (bundle["rf"], bundle["gb"], bundle["nn"],
bundle["scaler"], bundle["features"])
ET0 = max(0.0, (temperature - 20.0) * 0.1)
row = {
"soil_moisture": soil_moisture, "temperature": temperature,
"rainfall": rainfall, "irrigated_area": irrigated_area,
"region": region, "fertilizer_kg": fertilizer_kg,
"days_since_irrigation": days,
"soil_moisture_sq": soil_moisture**2,
"days_irrigation_sq": days**2,
"temp_rain_ratio": temperature / (rainfall + 0.1),
"et0_soil_interaction": ET0 * (1 - soil_moisture / 100),
}
for c in range(4): row[f"crop_{c}"] = int(crop_type == c)
for s in range(1,5): row[f"season_{s}"] = int(season == s)
for t in range(3): row[f"soil_{t}"] = int(soil_type == t)
X_in = np.array([[row.get(f, 0) for f in FEATS]])
X_in_sc = scaler.transform(X_in)
return (float(rf.predict(X_in)[0]),
float(gb.predict(X_in)[0]),
float(nn.predict(X_in_sc)[0]))
# ── Carte Burkina Faso (matplotlib) ──────────────────────────────────────────
def make_map(selected_region: str, irr_value: float = None):
fig, ax = plt.subplots(figsize=(5, 4))
fig.patch.set_facecolor("#EAF4F6")
ax.set_facecolor("#EAF4F6")
urgency_color = "#e74c3c" if (irr_value or 0) > 3 else "#e67e22" if (irr_value or 0) > 1.5 else "#27ae60"
for name, (lat, lon) in REGION_COORDS.items():
is_sel = (name == selected_region)
ax.scatter(lon, lat,
s=260 if is_sel else 80,
c=urgency_color if is_sel else "#0E5E6F",
zorder=5 if is_sel else 3,
edgecolors="white", linewidths=1.5)
offset_y = 0.18 if is_sel else 0.13
ax.text(lon, lat + offset_y, name,
ha="center", va="bottom",
fontsize=7.5 if is_sel else 5.5,
fontweight="bold" if is_sel else "normal",
color=urgency_color if is_sel else "#333",
zorder=6)
# Cadre Burkina Faso approx.
from matplotlib.patches import FancyBboxPatch
ax.set_xlim(-5.5, 2.4)
ax.set_ylim(9.4, 15.1)
ax.set_xlabel("Longitude", fontsize=7, color="#888")
ax.set_ylabel("Latitude", fontsize=7, color="#888")
ax.tick_params(labelsize=6, colors="#aaa")
for spine in ax.spines.values():
spine.set_edgecolor("#ccc")
# Légende urgence
if irr_value is not None:
urgency_lbl = "Urgent" if irr_value > 3 else "Modéré" if irr_value > 1.5 else "Favorable"
ax.set_title(f"📍 {selected_region} · {urgency_lbl} ({irr_value:.2f} mm/j)",
fontsize=8.5, fontweight="bold", color=urgency_color, pad=6)
plt.tight_layout(pad=0.5)
return fig
# ── Sidebar ───────────────────────────────────────────────────────────────────
with st.sidebar:
st.image("https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Flag_of_Burkina_Faso.svg/120px-Flag_of_Burkina_Faso.svg.png", width=50)
st.markdown("### 🌾 ARIA")
st.markdown("**Aide à la Recommandation d'Irrigation Agricole**")
st.markdown("---")
st.markdown("#### 📍 Localisation")
region_name = st.selectbox("Région", list(REGIONS.values()))
region_id = {v:k for k,v in REGIONS.items()}[region_name]
season_lbl = st.selectbox("Saison", list(SEASONS.values()))
season_id = {v:k for k,v in SEASONS.items()}[season_lbl]
st.markdown("#### 🌱 Culture & Sol")
crop_name = st.selectbox("Culture", list(CROPS.values()))
crop_id = {v:k for k,v in CROPS.items()}[crop_name]
soil_name = st.selectbox("Type de sol", list(SOIL_TYPES.values()))
soil_id = {v:k for k,v in SOIL_TYPES.items()}[soil_name]
st.markdown("#### 🌡️ Conditions climatiques")
temperature = st.slider("Température (°C)", 15, 50, 32)
rainfall = st.slider("Précipitations (mm/jour)", 0.0, 15.0, 1.0, 0.1)
soil_moist = st.slider("Humidité du sol (%)", 5, 95, 40)
st.markdown("#### 🚿 Pratiques agricoles")
irrig_area = st.slider("Surface irriguée (ha)", 0.5, 50.0, 5.0, 0.5)
fertilizer = st.slider("Engrais (kg/ha)", 0, 500, 80)
days_irrig = st.slider("Jours depuis dernière irrigation", 0, 30, 5)
st.markdown("---")
predict_btn = st.button("🔍 Calculer la recommandation", type="primary", use_container_width=True)
# ── Header ────────────────────────────────────────────────────────────────────
st.markdown("""
🌾 ARIA — Aide à la Recommandation d'Irrigation Agricole
Burkina Faso · 13 régions · 4 cultures · Machine Learning · DataBuilder Africa · 2026
""", unsafe_allow_html=True)
# ── Chargement ────────────────────────────────────────────────────────────────
with st.spinner("Chargement des modèles ML..."):
bundle = load_or_train_models()
df_raw = load_data()
if bundle is None:
st.error("Dataset introuvable. Placer `dataset_burkina_irrigation.csv` dans le même dossier.")
st.stop()
# ── Tabs ──────────────────────────────────────────────────────────────────────
tab1, tab2, tab3, tab4 = st.tabs([
"🔍 Recommandation",
"📊 Analyse des données",
"📈 Performances ML",
"ℹ️ À propos",
])
# ══════════════════════════════════════════════════════════════════════════════
# TAB 1 — Recommandation
# ══════════════════════════════════════════════════════════════════════════════
with tab1:
irr, yld, water = predict(
bundle, soil_moist, temperature, rainfall, crop_id,
irrig_area, season_id, region_id, soil_id, fertilizer, days_irrig
)
# ── Ligne 1 : Carte + Contexte ─────────────────────────────────────────
col_map, col_ctx = st.columns([1, 1], gap="large")
with col_map:
st.markdown("##### 📍 Localisation — " + region_name)
fig_map = make_map(region_name, irr)
st.pyplot(fig_map)
plt.close()
with col_ctx:
st.markdown("##### 📋 Situation analysée")
season_short = season_lbl.split("(")[0].strip()
st.markdown(f"""
📍 Région {region_name}
📅 Saison {season_short}
🌱 Culture {crop_name}
— {CROP_DESC[crop_id]}
🪨 Sol {soil_name}
— {SOIL_DESC[soil_id]}
""", unsafe_allow_html=True)
st.markdown(f"""
🌡️ Température {temperature} °C
🌧️ Pluie {rainfall} mm/j
💧 Humidité sol {soil_moist} %
🌿 Engrais {fertilizer} kg/ha
⏱️ Dernière irrigation il y a {days_irrig} jour(s)
""", unsafe_allow_html=True)
st.markdown("---")
# ── Ligne 2 : 3 Métriques ─────────────────────────────────────────────
st.markdown("##### 🤖 Prédictions des 3 modèles ML")
irr_color = "#e74c3c" if irr > 3 else "#e67e22" if irr > 1.5 else "#27ae60"
irr_label = "Élevé 🔴" if irr > 3 else "Modéré 🟠" if irr > 1.5 else "Faible 🟢"
irr_expl = ("Le sol est très sec. La culture manque d'eau. Irriguer rapidement." if irr > 3
else "Le sol commence à s'assécher. Une irrigation prochaine est conseillée." if irr > 1.5
else "Le sol est suffisamment humide. L'irrigation peut attendre.")
yld_color = "#27ae60" if yld > 2.0 else "#e67e22" if yld > 1.0 else "#e74c3c"
yld_expl = ("Bon rendement attendu avec les conditions actuelles." if yld > 2.0
else "Rendement moyen — une irrigation optimale peut l'améliorer." if yld > 1.0
else "Rendement faible prévu. Vérifier les apports en eau et engrais.")
eff_color = "#27ae60" if water > 0.5 else "#e67e22" if water > 0.25 else "#e74c3c"
eff_pct = min(100, int(water * 100))
eff_label = "Bonne 🟢" if water > 0.5 else "Moyenne 🟠" if water > 0.25 else "Faible 🔴"
eff_expl = ("L'eau est bien valorisée — chaque mm irrigué produit un bon rendement." if water > 0.5
else "L'efficacité est correcte mais peut être améliorée en ajustant les doses." if water > 0.25
else "L'eau est mal valorisée. Revoir la fréquence et la dose d'irrigation.")
m1, m2, m3 = st.columns(3, gap="medium")
with m1:
st.markdown(f"""
💧 Besoin d'irrigation
{irr:.2f} mm/jour
Niveau : {irr_label}
🔬 Prédit par Random Forest
{irr_expl}
""", unsafe_allow_html=True)
with m2:
st.markdown(f"""
🌾 Rendement agricole attendu
{yld:.2f} t/ha
Pour 1 hectare de {crop_name}
🔬 Prédit par Gradient Boosting
{yld_expl}
""", unsafe_allow_html=True)
with m3:
st.markdown(f"""
💦 Efficacité d'utilisation de l'eau
{eff_pct} %
Efficacité : {eff_label}
🔬 Prédit par Neural Network
{eff_expl}
""", unsafe_allow_html=True)
st.markdown("")
# ── Ligne 3 : Recommandation principale ───────────────────────────────
ET0 = max(0, (temperature - 20) * 0.1)
eau_eco = irr * 0.25
rev_add = yld * 500
if irr > 3.0:
reco_class = "reco-urgent"
reco_icon = "🚨"
reco_titre = "Irrigation urgente requise"
reco_corps = (f"Le besoin en eau est élevé ({irr:.2f} mm/jour). "
f"Votre champ de {crop_name} en {region_name} manque d'eau. "
f"Avec une humidité du sol à {soil_moist}% et une température de {temperature}°C, "
f"le sol se dessèche rapidement. "
f"Irriguer dans les 24 heures pour éviter des pertes de rendement. "
f"Rendement attendu si vous irriguez : {yld:.2f} t/ha.")
reco_action = f"⚡ Action immédiate : apporter {irr:.2f} mm/j · Économie possible avec optimisation : ~{eau_eco:.2f} mm/j"
elif irr > 1.5:
reco_class = "reco-modere"
reco_icon = "💧"
reco_titre = "Irrigation modérée recommandée"
reco_corps = (f"Le besoin en eau est modéré ({irr:.2f} mm/jour). "
f"Le sol est à {soil_moist}% d'humidité — correct mais en baisse. "
f"Programmer une irrigation dans les 2 à 3 jours pour maintenir le rendement. "
f"Le {crop_name} peut tolérer cette situation encore quelques jours sans perte majeure. "
f"Rendement attendu : {yld:.2f} t/ha.")
reco_action = f"📅 Action dans 2–3 jours : apporter {irr:.2f} mm/j · Revenu estimé : ~{rev_add:.0f} FCFA/ha"
else:
reco_class = "reco-ok"
reco_icon = "✅"
reco_titre = "Situation favorable — peu d'irrigation nécessaire"
reco_corps = (f"Le sol est bien humide ({soil_moist}%) et les précipitations ({rainfall} mm/j) "
f"couvrent une bonne partie des besoins. "
f"Le besoin d'irrigation résiduel est faible : {irr:.2f} mm/jour. "
f"Pas d'intervention urgente nécessaire. "
f"Surveiller l'évolution dans 3 à 5 jours. "
f"Rendement attendu : {yld:.2f} t/ha.")
reco_action = f"🔍 Surveiller dans 3–5 jours · Rendement attendu : {yld:.2f} t/ha · Efficacité eau : {eff_pct}%"
st.markdown(f"""
{reco_icon} {reco_titre}
{reco_corps}
{reco_action}
""", unsafe_allow_html=True)
st.markdown("")
# ── Ligne 4 : Comparaison cultures ────────────────────────────────────
with st.expander("📊 Comparer les 4 cultures dans ce même contexte"):
comp_rows = []
for cid, cname in CROPS.items():
i2, y2, w2 = predict(bundle, soil_moist, temperature, rainfall, cid,
irrig_area, season_id, region_id, soil_id, fertilizer, days_irrig)
comp_rows.append({"Culture": cname,
"Besoin irrigation (mm/j)": round(i2, 2),
"Rendement (t/ha)": round(y2, 2),
"Efficacité eau (%)": round(w2 * 100, 1),
"Sélectionnée": "◀ votre choix" if cname == crop_name else ""})
comp_df = pd.DataFrame(comp_rows)
fig, axes = plt.subplots(1, 3, figsize=(13, 3.5))
fig.patch.set_facecolor("#ffffff")
colors_bar = [CROP_COLORS[i] for i in range(4)]
sel_idx = list(CROPS.values()).index(crop_name)
for ax, col, unit, fmt in zip(
axes,
["Besoin irrigation (mm/j)", "Rendement (t/ha)", "Efficacité eau (%)"],
["mm/jour", "t/ha", "%"],
[".2f", ".2f", ".1f"]
):
bars = ax.bar(comp_df["Culture"], comp_df[col], color=colors_bar,
edgecolor="white", linewidth=0.8)
bars[sel_idx].set_edgecolor("#0E5E6F")
bars[sel_idx].set_linewidth(3)
ax.set_title(f"{col}\n({unit})", fontsize=9, fontweight='bold', color="#333")
ax.set_facecolor("#fafafa")
ax.tick_params(labelsize=8)
for b, v in zip(bars, comp_df[col]):
ax.text(b.get_x() + b.get_width()/2, b.get_height() + max(comp_df[col]) * 0.02,
f"{v:{fmt}}", ha='center', va='bottom', fontsize=8)
axes[0].set_ylabel("mm/jour", fontsize=8)
plt.tight_layout(pad=1.5)
st.pyplot(fig)
plt.close()
st.dataframe(comp_df, use_container_width=True, hide_index=True)
# ══════════════════════════════════════════════════════════════════════════════
# TAB 2 — Analyse des données
# ══════════════════════════════════════════════════════════════════════════════
with tab2:
if df_raw is None:
st.warning("Dataset non disponible.")
else:
st.markdown(f"**Dataset :** {len(df_raw):,} observations · 13 régions · 4 cultures · 2010–2022 · Source : NASA POWER / FAOSTAT / World Bank")
c1, c2, c3, c4 = st.columns(4)
c1.metric("Observations", f"{len(df_raw):,}")
c2.metric("Régions", f"{df_raw['region'].nunique()}")
c3.metric("Période", f"{int(df_raw['year'].min())}–{int(df_raw['year'].max())}")
c4.metric("Cultures", "4")
st.markdown("---")
st.markdown("#### 🗺️ Besoin moyen d'irrigation par région")
reg_df = df_raw.groupby("region_name")["irrigation_need_mm"].mean().sort_values(ascending=True).reset_index()
fig, ax = plt.subplots(figsize=(10, 5))
fig.patch.set_facecolor("#fafafa")
bars = ax.barh(reg_df["region_name"], reg_df["irrigation_need_mm"],
color=REGION_COLORS[:len(reg_df)], edgecolor="white")
ax.set_xlabel("Besoin moyen (mm/jour)")
ax.set_facecolor("#fafafa")
for b, v in zip(bars, reg_df["irrigation_need_mm"]):
ax.text(v + 0.01, b.get_y() + b.get_height()/2, f"{v:.2f}", va='center', fontsize=8)
plt.tight_layout()
st.pyplot(fig); plt.close()
col_a, col_b = st.columns(2)
with col_a:
st.markdown("#### 🌱 Besoin moyen par culture")
crop_df = df_raw.groupby("crop_name")["irrigation_need_mm"].mean().reset_index()
fig, ax = plt.subplots(figsize=(5, 3.5))
fig.patch.set_facecolor("#fafafa")
ax.bar(crop_df["crop_name"], crop_df["irrigation_need_mm"],
color=[CROP_COLORS[i] for i in range(4)], edgecolor="white")
ax.set_ylabel("mm/jour"); ax.set_facecolor("#fafafa")
plt.tight_layout(); st.pyplot(fig); plt.close()
with col_b:
st.markdown("#### 📅 Besoin moyen par saison")
slabels = {1:"Sèche", 2:"Pré-hivern.", 3:"Hivernage", 4:"Post-hivern."}
seas_df = df_raw.groupby("season")["irrigation_need_mm"].mean().reset_index()
seas_df["saison"] = seas_df["season"].map(slabels)
fig, ax = plt.subplots(figsize=(5, 3.5))
fig.patch.set_facecolor("#fafafa")
ax.bar(seas_df["saison"], seas_df["irrigation_need_mm"],
color=["#FF8C00","#90EE90","#4169E1","#DAA520"], edgecolor="white")
ax.set_ylabel("mm/jour"); ax.set_facecolor("#fafafa")
plt.tight_layout(); st.pyplot(fig); plt.close()
st.markdown("#### 🔗 Corrélation des variables numériques")
num_cols = ["soil_moisture","temperature","rainfall","fertilizer_kg",
"irrigation_need_mm","yield_predicted_tonnes_ha","water_efficiency"]
corr = df_raw[num_cols].corr()
fig, ax = plt.subplots(figsize=(8, 6))
fig.patch.set_facecolor("#fafafa")
mask = np.triu(np.ones_like(corr, dtype=bool))
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="RdYlGn",
center=0, ax=ax, linewidths=0.4, annot_kws={"size": 8})
plt.tight_layout(); st.pyplot(fig); plt.close()
st.markdown("#### 🗺️ Carte thermique : besoin d'irrigation (saison sèche)")
pivot = df_raw[df_raw["season"]==1].groupby(["region_name","crop_name"])["irrigation_need_mm"].mean().unstack()
fig, ax = plt.subplots(figsize=(8, 7))
fig.patch.set_facecolor("#fafafa")
sns.heatmap(pivot, annot=True, fmt=".2f", cmap="YlOrRd", ax=ax,
linewidths=0.4, cbar_kws={"label": "mm/jour"})
ax.set_xlabel("Culture"); ax.set_ylabel("Région")
plt.tight_layout(); st.pyplot(fig); plt.close()
# ══════════════════════════════════════════════════════════════════════════════
# TAB 3 — Performances ML
# ══════════════════════════════════════════════════════════════════════════════
with tab3:
perf = bundle["perf"]
st.markdown("#### Résultats sur le jeu de test (20 % des données)")
rows = [
{"Modèle":"Random Forest", "Cible":"Besoin d'irrigation (mm/j)", **perf["RF"]},
{"Modèle":"Gradient Boosting", "Cible":"Rendement agricole (t/ha)", **perf["GB"]},
{"Modèle":"Neural Network", "Cible":"Efficacité de l'eau [0–1]", **perf["NN"]},
]
perf_df = pd.DataFrame(rows)
cols = st.columns(3)
for col, (_, row) in zip(cols, perf_df.iterrows()):
r2_color = "#27ae60" if row["R2"] > 0.95 else "#e67e22"
with col:
st.markdown(f"""
{row['Modèle']}
R²={row['R2']:.4f}
{row['Cible']}
RMSE = {row['RMSE']:.5f} | MAE = {row['MAE']:.5f}
""", unsafe_allow_html=True)
st.markdown("")
st.dataframe(perf_df, use_container_width=True, hide_index=True)
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
fig.suptitle("Performances comparatives des 3 modèles", fontsize=11, fontweight='bold')
fig.patch.set_facecolor("#fafafa")
names = ["Random\nForest", "Gradient\nBoosting", "Neural\nNetwork"]
colors_perf = ["steelblue", "darkgreen", "purple"]
for ax, metric in zip(axes, ["R2","RMSE","MAE"]):
vals = [perf["RF"][metric], perf["GB"][metric], perf["NN"][metric]]
bars = ax.bar(names, vals, color=colors_perf, edgecolor="white")
ax.set_title(metric, fontweight='bold')
ax.set_facecolor("#fafafa")
for b, v in zip(bars, vals):
ax.text(b.get_x()+b.get_width()/2, b.get_height()+max(vals)*0.01,
f"{v:.4f}", ha='center', va='bottom', fontsize=8)
if metric == "R2":
ax.set_ylim(0, 1.05)
ax.axhline(0.95, color='red', ls='--', lw=1, label="Seuil 0.95")
ax.legend(fontsize=8)
plt.tight_layout()
st.pyplot(fig); plt.close()
st.markdown("#### Top 15 features — Random Forest")
fi = pd.Series(bundle["rf"].feature_importances_, index=bundle["features"]).nlargest(15).sort_values()
fig, ax = plt.subplots(figsize=(9, 5))
fig.patch.set_facecolor("#fafafa")
fi.plot(kind="barh", ax=ax, color="steelblue")
ax.set_xlabel("Importance"); ax.set_facecolor("#fafafa")
plt.tight_layout(); st.pyplot(fig); plt.close()
# ══════════════════════════════════════════════════════════════════════════════
# TAB 4 — À propos
# ══════════════════════════════════════════════════════════════════════════════
with tab4:
col1, col2 = st.columns([2, 1])
with col1:
st.markdown("""
## ARIA — Aide à la Recommandation d'Irrigation Agricole
### Problème
Le Burkina Faso fait face à un double défi :
- **Gaspillage d'eau** : 30–40 % de l'eau d'irrigation s'évapore inutilement
- **Rendements imprévisibles** : pertes de 20–40 % dues à une irrigation inadaptée
### Solution
Un système ML qui prédit pour chaque parcelle :
1. **Le besoin d'irrigation optimal** (mm/jour) — Random Forest
2. **Le rendement attendu** (t/ha) — Gradient Boosting
3. **L'efficacité de l'eau** (%) — Neural Network
### Sources de données réelles
| Source | Type | Couverture |
|--------|------|-----------|
| NASA POWER API | Climatique réel (T°, pluie, humidité sol) | 2010–2022, 13 régions |
| FAOSTAT | Rendements agricoles Burkina Faso | 2010–2022 |
| World Bank API | Indicateurs d'engrais | 2010–2022 |
### Impact attendu
- **20–30 %** d'économies d'eau
- **+15–20 %** d'augmentation des rendements
- **5 millions** d'agriculteurs concernés au Burkina Faso
""")
with col2:
st.markdown("""
### Performances ML (jeu de test)
| Modèle | R² |
|--------|-----|
| Random Forest | **0,9994** |
| Gradient Boosting | **0,9294** |
| Neural Network | **0,8691** |
### Dataset
```
24 336 observations
22 features
13 régions
4 cultures
3 types de sol
2010 – 2022
```
""")
st.markdown("---")
st.markdown("""
**DataBuilder Africa** · ARIA — Aide à la Recommandation d'Irrigation Agricole
Données : NASA POWER · FAOSTAT · World Bank
Stack : Python · scikit-learn · Streamlit · Plotly
""")
# ── Footer ────────────────────────────────────────────────────────────────────
st.markdown("---")
st.markdown(
""
"ARIA — Aide à la Recommandation d'Irrigation Agricole · DataBuilder Africa · Burkina Faso 2026 · "
"Données : NASA POWER · FAOSTAT · World Bank"
"
",
unsafe_allow_html=True
)