cheikhaidev-ui commited on
Commit ·
1c045e4
1
Parent(s): 0d55d9d
perf: vectorize data generation and batch map predictions (batch 2/3)
Browse files- perf(data_generator): replace 52,560-iter Python loop with numpy vectorized ops (~20-50x faster)
- perf(supabase): replace iterrows() with to_dict('records'), add timeout=30, exponential backoff on error
- perf(app): batch 8 map predictions into single numpy matrix call (8x fewer model invocations)
- fix(app): initialize results=[] before model availability check to prevent NameError
- scripts/3_load_to_supabase.py +18 -21
- src/data_generator.py +75 -51
- streamlit_app/app.py +36 -8
scripts/3_load_to_supabase.py
CHANGED
|
@@ -59,43 +59,40 @@ error_count = 0
|
|
| 59 |
for i in range(0, len(df), batch_size):
|
| 60 |
batch_num = i // batch_size + 1
|
| 61 |
batch = df[i:i + batch_size]
|
| 62 |
-
|
| 63 |
-
# Préparer les données
|
| 64 |
-
records =
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
'prediction': int(row['coupure'])
|
| 74 |
-
})
|
| 75 |
-
|
| 76 |
# Envoyer à Supabase
|
| 77 |
try:
|
| 78 |
response = requests.post(
|
| 79 |
f"{url}/rest/v1/enregistrements",
|
| 80 |
headers=headers,
|
| 81 |
-
json=records
|
|
|
|
| 82 |
)
|
| 83 |
-
|
| 84 |
if response.status_code in [200, 201]:
|
| 85 |
success_count += len(records)
|
| 86 |
print(f" ✅ Batch {batch_num}/{total_batches} : {len(records)} lignes")
|
| 87 |
else:
|
| 88 |
error_count += len(records)
|
| 89 |
print(f" ❌ Batch {batch_num}/{total_batches} : Erreur {response.status_code}")
|
| 90 |
-
if batch_num == 1:
|
| 91 |
print(f" {response.text[:200]}")
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
time.sleep(0.5)
|
| 95 |
-
|
| 96 |
except Exception as e:
|
| 97 |
error_count += len(records)
|
| 98 |
print(f" ❌ Batch {batch_num}/{total_batches} : {e}")
|
|
|
|
| 99 |
|
| 100 |
print("\n" + "=" * 70)
|
| 101 |
print("📊 RÉSUMÉ")
|
|
|
|
| 59 |
for i in range(0, len(df), batch_size):
|
| 60 |
batch_num = i // batch_size + 1
|
| 61 |
batch = df[i:i + batch_size]
|
| 62 |
+
|
| 63 |
+
# Préparer les données via rename + to_dict (pas d'iterrows)
|
| 64 |
+
records = (
|
| 65 |
+
batch.rename(columns={'date': 'date_heure', 'coupure': 'prediction'})
|
| 66 |
+
[['date_heure', 'quartier', 'temp_celsius', 'humidite_percent',
|
| 67 |
+
'vitesse_vent', 'conso_megawatt', 'prediction']]
|
| 68 |
+
.astype({'temp_celsius': float, 'humidite_percent': int,
|
| 69 |
+
'vitesse_vent': float, 'conso_megawatt': int, 'prediction': int})
|
| 70 |
+
.to_dict('records')
|
| 71 |
+
)
|
| 72 |
+
|
|
|
|
|
|
|
|
|
|
| 73 |
# Envoyer à Supabase
|
| 74 |
try:
|
| 75 |
response = requests.post(
|
| 76 |
f"{url}/rest/v1/enregistrements",
|
| 77 |
headers=headers,
|
| 78 |
+
json=records,
|
| 79 |
+
timeout=30
|
| 80 |
)
|
| 81 |
+
|
| 82 |
if response.status_code in [200, 201]:
|
| 83 |
success_count += len(records)
|
| 84 |
print(f" ✅ Batch {batch_num}/{total_batches} : {len(records)} lignes")
|
| 85 |
else:
|
| 86 |
error_count += len(records)
|
| 87 |
print(f" ❌ Batch {batch_num}/{total_batches} : Erreur {response.status_code}")
|
| 88 |
+
if batch_num == 1:
|
| 89 |
print(f" {response.text[:200]}")
|
| 90 |
+
time.sleep(min(2 ** (error_count // batch_size), 30)) # backoff sur erreur uniquement
|
| 91 |
+
|
|
|
|
|
|
|
| 92 |
except Exception as e:
|
| 93 |
error_count += len(records)
|
| 94 |
print(f" ❌ Batch {batch_num}/{total_batches} : {e}")
|
| 95 |
+
time.sleep(2)
|
| 96 |
|
| 97 |
print("\n" + "=" * 70)
|
| 98 |
print("📊 RÉSUMÉ")
|
src/data_generator.py
CHANGED
|
@@ -310,74 +310,98 @@ def generate_dataset(
|
|
| 310 |
"""
|
| 311 |
if quartiers is None:
|
| 312 |
quartiers = list(QUARTIERS_CONFIG.keys())
|
| 313 |
-
|
| 314 |
print("=" * 70)
|
| 315 |
-
print(" 🔄 GÉNÉRATION DES DONNÉES SYNTHÉTIQUES")
|
| 316 |
print("=" * 70)
|
| 317 |
print(f"📅 Période : {start_date} → {end_date}")
|
| 318 |
print(f"🏘️ Quartiers : {len(quartiers)}")
|
| 319 |
-
|
| 320 |
-
# Générer les dates
|
| 321 |
dates = generate_date_range(start_date, end_date, freq='1H')
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
for quartier in quartiers:
|
| 327 |
print(f"\n📍 Génération pour {quartier}...")
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
print("\n" + "=" * 70)
|
| 369 |
print(" ✅ GÉNÉRATION TERMINÉE")
|
| 370 |
print("=" * 70)
|
| 371 |
print(f"📊 Total lignes : {len(df):,}")
|
| 372 |
print(f"🔴 Coupures : {df['coupure'].sum():,} ({df['coupure'].mean()*100:.2f}%)")
|
| 373 |
print(f"🟢 Pas de coupure : {(~df['coupure'].astype(bool)).sum():,}")
|
| 374 |
-
|
| 375 |
-
# Taux par quartier
|
| 376 |
print("\n📊 Taux de coupure par quartier :")
|
| 377 |
for quartier in quartiers:
|
| 378 |
taux = df[df['quartier'] == quartier]['coupure'].mean() * 100
|
| 379 |
print(f" {quartier:25s} : {taux:6.2f}%")
|
| 380 |
-
|
| 381 |
return df
|
| 382 |
|
| 383 |
|
|
|
|
| 310 |
"""
|
| 311 |
if quartiers is None:
|
| 312 |
quartiers = list(QUARTIERS_CONFIG.keys())
|
| 313 |
+
|
| 314 |
print("=" * 70)
|
| 315 |
+
print(" 🔄 GÉNÉRATION DES DONNÉES SYNTHÉTIQUES (vectorisée)")
|
| 316 |
print("=" * 70)
|
| 317 |
print(f"📅 Période : {start_date} → {end_date}")
|
| 318 |
print(f"🏘️ Quartiers : {len(quartiers)}")
|
| 319 |
+
|
|
|
|
| 320 |
dates = generate_date_range(start_date, end_date, freq='1H')
|
| 321 |
+
n = len(dates)
|
| 322 |
+
print(f"⏰ Timestamps : {n:,}")
|
| 323 |
+
|
| 324 |
+
# Composantes temporelles extraites une seule fois pour tous les quartiers
|
| 325 |
+
hours = dates.hour.values
|
| 326 |
+
months = dates.month.values
|
| 327 |
+
days_of_week = dates.dayofweek.values
|
| 328 |
+
|
| 329 |
+
# Saison vectorielle — identique à get_season()
|
| 330 |
+
seasons = np.where(np.isin(months, [11, 12, 1, 2]), 0,
|
| 331 |
+
np.where(np.isin(months, [3, 4, 5]), 1, 2))
|
| 332 |
+
|
| 333 |
+
# Heure de pointe vectorielle — identique à is_peak_hour()
|
| 334 |
+
is_peak = ((hours >= 7) & (hours <= 9)) | ((hours >= 18) & (hours <= 21))
|
| 335 |
+
|
| 336 |
+
frames = []
|
| 337 |
for quartier in quartiers:
|
| 338 |
print(f"\n📍 Génération pour {quartier}...")
|
| 339 |
+
cfg = QUARTIERS_CONFIG[quartier]
|
| 340 |
+
|
| 341 |
+
# Température (vectorise generate_temperature)
|
| 342 |
+
season_base = np.where(seasons == 0, 24.0, np.where(seasons == 1, 30.0, 27.0))
|
| 343 |
+
hour_effect = 5 * np.sin((hours - 6) * np.pi / 12)
|
| 344 |
+
temp = np.round(np.clip(
|
| 345 |
+
season_base + hour_effect + cfg['temperature_bias'] + np.random.normal(0, 2, n),
|
| 346 |
+
18, 42
|
| 347 |
+
), 2)
|
| 348 |
+
|
| 349 |
+
# Humidité (vectorise generate_humidity)
|
| 350 |
+
hum_season_adj = np.where(seasons == 2, 15, np.where(seasons == 1, -10, 0))
|
| 351 |
+
humidity = np.clip(
|
| 352 |
+
100 - (temp - 20) * 1.5 + hum_season_adj + np.random.normal(0, 8, n),
|
| 353 |
+
30, 95
|
| 354 |
+
).astype(int)
|
| 355 |
+
|
| 356 |
+
# Vent (vectorise generate_wind_speed)
|
| 357 |
+
wind_base = np.where(seasons == 2, 20.0, 12.0) + np.where(is_peak, 5.0, 0.0)
|
| 358 |
+
wind = np.round(np.clip(wind_base + np.random.normal(0, 5, n), 0, 50), 2)
|
| 359 |
+
|
| 360 |
+
# Consommation (vectorise generate_consumption)
|
| 361 |
+
hour_factor = np.where(is_peak, 1.3, np.where((hours >= 22) | (hours <= 5), 0.7, 1.0))
|
| 362 |
+
temp_factor = np.where(temp > 32, 1 + (temp - 32) * 0.03, 1.0)
|
| 363 |
+
consumption = np.clip(
|
| 364 |
+
cfg['consommation_avg'] * hour_factor * temp_factor + np.random.normal(0, 50, n),
|
| 365 |
+
200, 1500
|
| 366 |
+
).astype(int)
|
| 367 |
+
|
| 368 |
+
# Probabilité de coupure (vectorise calculate_outage_probability)
|
| 369 |
+
temp_risk = np.where(temp < 30, 0.0, (temp - 30) * 0.02)
|
| 370 |
+
conso_risk = np.where(consumption < 900, 0.0, (consumption - 900) * 0.0001)
|
| 371 |
+
peak_risk = np.where(is_peak, 0.03, 0.0)
|
| 372 |
+
season_risk = np.where(seasons == 1, 0.02, 0.0)
|
| 373 |
+
proba = np.clip(cfg['risque_base'] + temp_risk + conso_risk + peak_risk + season_risk, 0, 1)
|
| 374 |
+
coupure = (np.random.random(n) < proba).astype(int)
|
| 375 |
+
|
| 376 |
+
frames.append(pd.DataFrame({
|
| 377 |
+
'date_heure': dates,
|
| 378 |
+
'quartier': quartier,
|
| 379 |
+
'temp_celsius': temp,
|
| 380 |
+
'humidite_percent': humidity,
|
| 381 |
+
'vitesse_vent': wind,
|
| 382 |
+
'conso_megawatt': consumption,
|
| 383 |
+
'heure': hours,
|
| 384 |
+
'jour_semaine': days_of_week,
|
| 385 |
+
'mois': months,
|
| 386 |
+
'saison': seasons,
|
| 387 |
+
'is_peak_hour': is_peak.astype(int),
|
| 388 |
+
'coupure': coupure,
|
| 389 |
+
}))
|
| 390 |
+
|
| 391 |
+
df = pd.concat(frames, ignore_index=True)
|
| 392 |
+
|
| 393 |
print("\n" + "=" * 70)
|
| 394 |
print(" ✅ GÉNÉRATION TERMINÉE")
|
| 395 |
print("=" * 70)
|
| 396 |
print(f"📊 Total lignes : {len(df):,}")
|
| 397 |
print(f"🔴 Coupures : {df['coupure'].sum():,} ({df['coupure'].mean()*100:.2f}%)")
|
| 398 |
print(f"🟢 Pas de coupure : {(~df['coupure'].astype(bool)).sum():,}")
|
| 399 |
+
|
|
|
|
| 400 |
print("\n📊 Taux de coupure par quartier :")
|
| 401 |
for quartier in quartiers:
|
| 402 |
taux = df[df['quartier'] == quartier]['coupure'].mean() * 100
|
| 403 |
print(f" {quartier:25s} : {taux:6.2f}%")
|
| 404 |
+
|
| 405 |
return df
|
| 406 |
|
| 407 |
|
streamlit_app/app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import logging
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
from pathlib import Path
|
| 6 |
import sys
|
|
@@ -20,7 +21,7 @@ from streamlit_app.utils_simple import (
|
|
| 20 |
create_temporal_chart,
|
| 21 |
create_risk_trend_chart,
|
| 22 |
)
|
| 23 |
-
from src.config import QUARTIERS_DAKAR
|
| 24 |
|
| 25 |
st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
|
| 26 |
|
|
@@ -139,14 +140,41 @@ with tab2:
|
|
| 139 |
st.header("🗺️ Carte Interactive")
|
| 140 |
if st.button("🔄 Calculer pour tous les quartiers"):
|
| 141 |
time_features = create_time_features(datetime.now())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
results = []
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
if results:
|
| 151 |
fig = create_map(results)
|
| 152 |
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': True})
|
|
|
|
| 1 |
import logging
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
from datetime import datetime
|
| 6 |
from pathlib import Path
|
| 7 |
import sys
|
|
|
|
| 21 |
create_temporal_chart,
|
| 22 |
create_risk_trend_chart,
|
| 23 |
)
|
| 24 |
+
from src.config import QUARTIERS_DAKAR, QUARTIER_ADJUSTMENT
|
| 25 |
|
| 26 |
st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
|
| 27 |
|
|
|
|
| 140 |
st.header("🗺️ Carte Interactive")
|
| 141 |
if st.button("🔄 Calculer pour tous les quartiers"):
|
| 142 |
time_features = create_time_features(datetime.now())
|
| 143 |
+
lgb_model = models['lgb']
|
| 144 |
+
lstm_model = models['lstm']
|
| 145 |
+
scaler = models['scaler']
|
| 146 |
+
|
| 147 |
results = []
|
| 148 |
+
if lgb_model is None or scaler is None:
|
| 149 |
+
st.error("Modèles non chargés — impossible de calculer la carte.")
|
| 150 |
+
else:
|
| 151 |
+
# Matrice 8×9 : une ligne par quartier, mêmes features météo pour tous
|
| 152 |
+
feature_row = [
|
| 153 |
+
temperature, humidite, vitesse_vent, consommation,
|
| 154 |
+
time_features['hour'], time_features['day_of_week'],
|
| 155 |
+
time_features['month'], time_features['saison'],
|
| 156 |
+
time_features['is_peak_hour'],
|
| 157 |
+
]
|
| 158 |
+
X = np.tile(feature_row, (len(QUARTIERS_DAKAR), 1)) # (8, 9)
|
| 159 |
+
X_scaled = scaler.transform(X) # une seule passe
|
| 160 |
+
|
| 161 |
+
preds_lgb = lgb_model.predict(X_scaled) * 100 # (8,) en un appel
|
| 162 |
+
|
| 163 |
+
if lstm_model is not None:
|
| 164 |
+
X_lstm = X_scaled.reshape(len(QUARTIERS_DAKAR), 1, -1) # (8, 1, 9)
|
| 165 |
+
preds_lstm = lstm_model.predict(X_lstm, verbose=0).flatten() * 100
|
| 166 |
+
else:
|
| 167 |
+
preds_lstm = preds_lgb.copy()
|
| 168 |
+
|
| 169 |
+
risque_base = (preds_lgb + preds_lstm) / 2
|
| 170 |
+
|
| 171 |
+
results = [
|
| 172 |
+
{
|
| 173 |
+
'Quartier': q,
|
| 174 |
+
'Risque': float(np.clip(risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0), 0, 100)),
|
| 175 |
+
}
|
| 176 |
+
for i, q in enumerate(QUARTIERS_DAKAR)
|
| 177 |
+
]
|
| 178 |
if results:
|
| 179 |
fig = create_map(results)
|
| 180 |
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': True})
|