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 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
- for _, row in batch.iterrows():
66
- records.append({
67
- 'date_heure': row['date'],
68
- 'quartier': row['quartier'],
69
- 'temp_celsius': float(row['temp_celsius']),
70
- 'humidite_percent': int(row['humidite_percent']),
71
- 'vitesse_vent': float(row['vitesse_vent']),
72
- 'conso_megawatt': int(row['conso_megawatt']),
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: # Afficher détails pour première erreur
91
  print(f" {response.text[:200]}")
92
-
93
- # Pause pour éviter rate limit
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
- print(f"⏰ Timestamps : {len(dates):,}")
323
-
324
- data = []
325
-
 
 
 
 
 
 
 
 
 
 
 
 
326
  for quartier in quartiers:
327
  print(f"\n📍 Génération pour {quartier}...")
328
- config = QUARTIERS_CONFIG[quartier]
329
-
330
- for date in dates:
331
- hour = date.hour
332
- month = date.month
333
- day_of_week = date.dayofweek
334
- season = get_season(month)
335
- is_peak = is_peak_hour(hour)
336
-
337
- # Générer les features
338
- temp = generate_temperature(month, hour, config)
339
- humidity = generate_humidity(temp, season)
340
- wind = generate_wind_speed(season, is_peak)
341
- consumption = generate_consumption(hour, is_peak, config, temp)
342
-
343
- # Calculer probabilité de coupure
344
- proba = calculate_outage_probability(
345
- temp, humidity, wind, consumption, is_peak, config, season
346
- )
347
-
348
- # Déterminer s'il y a coupure
349
- coupure = 1 if np.random.random() < proba else 0
350
-
351
- data.append({
352
- 'date_heure': date,
353
- 'quartier': quartier,
354
- 'temp_celsius': round(temp, 2),
355
- 'humidite_percent': humidity,
356
- 'vitesse_vent': round(wind, 2),
357
- 'conso_megawatt': consumption,
358
- 'heure': hour,
359
- 'jour_semaine': day_of_week,
360
- 'mois': month,
361
- 'saison': season,
362
- 'is_peak_hour': int(is_peak),
363
- 'coupure': coupure
364
- })
365
-
366
- df = pd.DataFrame(data)
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
- progress = st.progress(0)
144
- for i, q in enumerate(QUARTIERS_DAKAR):
145
- result = make_prediction_single(models, q, temperature, humidite, vitesse_vent, consommation, time_features)
146
- if result:
147
- results.append({'Quartier': q, 'Risque': result[2]})
148
- progress.progress((i + 1) / len(QUARTIERS_DAKAR))
149
- progress.empty()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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})