-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.py
More file actions
567 lines (487 loc) · 22.2 KB
/
interface.py
File metadata and controls
567 lines (487 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import os
import datetime
import numpy as np
import pandas as pd
import geopandas as gpd
import folium
import streamlit as st
import main as main_module # simulateur
import fonction_calcul_trajet as fct
from classes import Secteur, POMPE_Engin, PSE_Engin, VSAV_Engin
from data import get_engins as get_engins_data, get_secteurs, get_interventions, get_indisponibilites, get_raw_secteurs
# Laisser geopandas/pyogrio résoudre GDAL_DATA automatiquement.
# Si nécessaire, définir GDAL_DATA dans l'environnement avant de lancer.
# -----------------------------
# PAGE CONFIG
# -----------------------------
st.set_page_config(layout="wide")
# Masquer le message "press enter to apply" des number_input
st.markdown("""
<style>
[data-testid="stNumberInputContainer"] [data-testid="InputInstructions"] {
display: none;
}
</style>
""", unsafe_allow_html=True)
# En-tête avec logo
col_title, col_logo = st.columns([4, 1])
with col_title:
st.title("Jumeau numérique de la BSPP")
with col_logo:
st.image("images/Reflets.png", width=150)
# -----------------------------
# HELPERS
# -----------------------------
def normalize_type_vhl(type_value: str) -> str:
if not isinstance(type_value, str):
return "UNKNOWN"
if type_value.endswith("_Engin"):
type_value = type_value.replace("_Engin", "")
if type_value in {"POMPE", "PSE", "VSAV"}:
return type_value
return type_value
def _to_date(d):
if d is None:
return None
if isinstance(d, (list, tuple, np.ndarray)):
if len(d) == 0:
return None
d = d[0]
try:
if isinstance(d, pd.Timestamp):
return d.date()
except Exception:
pass
try:
if isinstance(d, (np.datetime64,)):
return pd.to_datetime(d).date()
except Exception:
pass
if isinstance(d, datetime.datetime):
return d.date()
if isinstance(d, datetime.date):
return d
try:
return pd.to_datetime(d).date()
except Exception:
return None
def convert_session_engins_to_objects():
"""
Convertit la liste st.session_state.engins en dictionnaire d'objets Engin.
Crée de nouveaux objets Engin pour les IDs qui n'existent pas dans engins_base.
"""
engins_dict = {}
type_class_map = {
'POMPE_Engin': POMPE_Engin,
'PSE_Engin': PSE_Engin,
'VSAV_Engin': VSAV_Engin
}
for engin_state in st.session_state.engins:
engin_id = engin_state['id']
engin_cs = engin_state['cs']
engin_type = engin_state['type']
# Si l'engin existe dans la base, utiliser l'objet existant
if engin_id in st.session_state.engins_base:
engin_obj = st.session_state.engins_base[engin_id]
engin_obj.cs = engin_cs # Mettre à jour le CS
engin_obj.reset_simulation_state() # Nettoyer l'état de la simulation précédente
engins_dict[engin_id] = engin_obj
else:
# Créer un nouvel objet Engin
if engin_type in type_class_map:
EnginClass = type_class_map[engin_type]
# Récupérer les coordonnées du CS depuis les secteurs
secteurs = get_secteurs()
if engin_cs in secteurs:
x_cs = secteurs[engin_cs].x
y_cs = secteurs[engin_cs].y
else:
# Fallback: coordonnées par défaut (ANTO)
x_cs, y_cs = 0.0, 0.0
new_engin = EnginClass(engin_id, engin_cs, x_cs, y_cs)
new_engin.indisponibilites.set_up() # Initialiser les indispos vides
engins_dict[engin_id] = new_engin
return engins_dict
# -----------------------------
# STATE INITIALIZATION
# -----------------------------
if "engins" not in st.session_state:
engins_initiaux = get_engins_data()
st.session_state.engins = [
{
"id": e,
"cs": engins_initiaux[e].cs,
"nom": f"{engins_initiaux[e]}",
"type": type(engins_initiaux[e]).__name__,
}
for e in engins_initiaux
]
if "engins_initial" not in st.session_state:
st.session_state.engins_initial = [dict(eng) for eng in st.session_state.engins]
if "progress" not in st.session_state:
st.session_state.progress = 0
if "allocation_dirty" not in st.session_state:
st.session_state.allocation_dirty = False
if "simulation_time" not in st.session_state:
st.session_state.simulation_time = None
# Pré-chargement des interventions et indisponibilités au démarrage
if "interventions_data" not in st.session_state:
with st.spinner("⏳ Chargement des interventions..."):
st.session_state.interventions_data = get_interventions()
st.session_state.indisponibilites_data = get_indisponibilites()
# Pré-chargement de la base d'engins pour les boutons +/-
if "engins_base" not in st.session_state:
st.session_state.engins_base = get_engins_data()
# -----------------------------
# LOAD SECTEURS
# -----------------------------
@st.cache_data
def load_secteurs_and_gdf():
secteurs = get_secteurs()
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
GEOJSON_PATH = os.path.join(SCRIPT_DIR, "datas/geo/secteurs_cs.geojson")
gdf = gpd.read_file(GEOJSON_PATH)
return secteurs, gdf
secteurs_initiaux, gdf = load_secteurs_and_gdf()
# Streamlit cache can skip get_secteurs side effects; ensure Secteur.df is set.
if not hasattr(Secteur, "df") or Secteur.df is None:
Secteur.df = get_raw_secteurs()
# -----------------------------
# SIDEBAR
# -----------------------------
st.sidebar.title("⚙️ Paramètres")
date_range = st.sidebar.date_input(
"Durée de simulation (début, fin)",
value=[datetime.date(2023, 1, 1), datetime.date(2023, 1, 15)]
)
if isinstance(date_range, (list, tuple)) and len(date_range) == 2:
sim_start_date, sim_end_date = date_range
else:
sim_start_date = sim_end_date = date_range
sim_start_date = _to_date(sim_start_date)
sim_end_date = _to_date(sim_end_date)
if sim_start_date is None and sim_end_date is None:
sim_start_date = sim_end_date = datetime.date.today()
elif sim_start_date is None:
sim_start_date = sim_end_date
elif sim_end_date is None:
sim_end_date = sim_start_date
st.session_state["simulation_start"] = datetime.datetime.combine(sim_start_date, datetime.time.min)
st.session_state["simulation_end"] = datetime.datetime.combine(sim_end_date, datetime.time.max)
# -----------------------------
# CARTE ALLOCATION COURANTE
# -----------------------------
st.markdown("---")
st.subheader("Allocation courante")
_TYPE_MAP_DISPLAY = {"POMPE_Engin": "POMPE", "PSE_Engin": "PSE", "VSAV_Engin": "VSAV"}
_ICON_MAP = {
"POMPE": ("🚒", "#d62728"),
"VSAV": ("🚑", "#1f77b4"),
"PSE": ("⛑", "#2ca02c"),
}
_alloc_rows = []
for e in st.session_state.engins:
cs = e.get("cs", "ANTO")
tp = _TYPE_MAP_DISPLAY.get(e.get("type", ""), e.get("type", "?"))
sx = secteurs_initiaux[cs].x if cs in secteurs_initiaux else np.nan
sy = secteurs_initiaux[cs].y if cs in secteurs_initiaux else np.nan
_alloc_rows.append({"id": e.get("id"), "cs": cs, "type_vhl": tp, "x": sx, "y": sy})
_df_alloc = pd.DataFrame(_alloc_rows)
col_s1, col_s2, col_s3, col_s4 = st.columns(4)
col_s1.metric("Vehicules", len(_df_alloc))
col_s2.metric("POMPE", int((_df_alloc["type_vhl"] == "POMPE").sum()))
col_s3.metric("VSAV", int((_df_alloc["type_vhl"] == "VSAV").sum()))
col_s4.metric("PSE", int((_df_alloc["type_vhl"] == "PSE").sum()))
_cs_groups = _df_alloc.groupby("cs").agg(
x=("x", "first"), y=("y", "first"),
nb_pompe=("type_vhl", lambda s: (s == "POMPE").sum()),
nb_vsav=("type_vhl", lambda s: (s == "VSAV").sum()),
nb_pse=("type_vhl", lambda s: (s == "PSE").sum()),
total=("id", "count"),
).reset_index()
_m = folium.Map(location=[48.8566, 2.3522], zoom_start=11)
folium.GeoJson(
gdf,
style_function=lambda f: {"fillColor": "#f0f0f0", "color": "#999999", "weight": 1, "fillOpacity": 0.25},
tooltip=folium.GeoJsonTooltip(fields=["nom"], aliases=["Secteur"]),
).add_to(_m)
for _, _row in _cs_groups.iterrows():
if pd.isna(_row["x"]) or pd.isna(_row["y"]):
continue
nb_p, nb_v, nb_s = int(_row["nb_pompe"]), int(_row["nb_vsav"]), int(_row["nb_pse"])
total = int(_row["total"])
trucks = []
for _ in range(nb_p): trucks.append(_ICON_MAP["POMPE"])
for _ in range(nb_v): trucks.append(_ICON_MAP["VSAV"])
for _ in range(nb_s): trucks.append(_ICON_MAP["PSE"])
cols_per = min(5, max(1, total))
truck_html = ""
for i, (icon, color) in enumerate(trucks):
truck_html += f'<span style="font-size:11px;filter:drop-shadow(0 0 1px {color});">{icon}</span>'
if (i + 1) % cols_per == 0 and i < len(trucks) - 1:
truck_html += "<br>"
icon_html = f"""<div style="background:rgba(255,255,255,0.92);border:1.5px solid #555;
border-radius:6px;padding:2px 4px;text-align:center;line-height:1.3;white-space:nowrap;">
<div style="font-weight:bold;font-size:9px;color:#333;margin-bottom:1px;">{_row['cs']}</div>
<div>{truck_html}</div></div>"""
popup_html = f"""<div style="font-family:sans-serif;font-size:13px;">
<b>{_row['cs']}</b><br><br>
<span style='color:#d62728'>🚒 POMPE: {nb_p}</span><br>
<span style='color:#1f77b4'>🚑 VSAV: {nb_v}</span><br>
<span style='color:#2ca02c'>⛑ PSE: {nb_s}</span><br>
<br><b>Total: {total}</b></div>"""
icon_w = max(45, cols_per * 16 + 12)
icon_h = max(30, 18 + ((total - 1) // cols_per + 1) * 16)
folium.Marker(
location=[_row["y"], _row["x"]],
icon=folium.DivIcon(html=icon_html, icon_size=(icon_w, icon_h), icon_anchor=(icon_w // 2, icon_h // 2)),
popup=folium.Popup(popup_html, max_width=220),
tooltip=f"{_row['cs']} ({total} vhl)",
).add_to(_m)
st.components.v1.html(_m._repr_html_(), width=900, height=500)
df_interventions = None
# --- Sidebar : Upload CSV interventions ---
with st.sidebar.expander("Upload CSV interventions"):
uploaded_file = st.file_uploader("Choisir un CSV", type=["csv", "parquet"], key="upload_inter")
if uploaded_file:
try:
if uploaded_file.name.endswith(".parquet"):
df_interventions = pd.read_parquet(uploaded_file)
else:
df_interventions = pd.read_csv(uploaded_file)
st.success(f"{len(df_interventions)} lignes chargees")
except Exception as e:
st.error(f"Erreur: {e}")
if df_interventions is not None and "custom_inter_parsed" not in st.session_state:
st.info("Cliquer sur 'Charger' pour parser et pre-calculer les temps de trajet.")
if st.button("Charger", key="btn_load_custom"):
from data import parse_custom_interventions_csv
with st.spinner("Parsing des interventions..."):
custom_inter = parse_custom_interventions_csv(df_interventions)
st.session_state.custom_interventions = custom_inter
# Pre-calcul des matrices de trajet
with st.spinner(f"Pre-calcul temps de trajet ({len(custom_inter)} inter x {len(fct.get_cs_list())} CS)..."):
x_arr = np.array([i.x for i in custom_inter])
y_arr = np.array([i.y for i in custom_inter])
xf_arr = np.array([i.x_final for i in custom_inter])
yf_arr = np.array([i.y_final for i in custom_inter])
hours_arr = np.array([i.date.hour for i in custom_inter])
weekends_arr = np.array([i.date.weekday() >= 5 for i in custom_inter])
mat_a, mat_r = fct.precompute_for_custom_interventions(
x_arr, y_arr, xf_arr, yf_arr, hours_arr, weekends_arr
)
if mat_a is not None:
fct.register_custom_matrices(mat_a, mat_r, x_arr, y_arr, xf_arr, yf_arr)
st.session_state.custom_inter_parsed = True
st.success(f"{len(custom_inter)} interventions chargees et pre-calculees !")
st.rerun()
if st.session_state.get("custom_inter_parsed"):
n = len(st.session_state.get("custom_interventions", []))
st.caption(f"Interventions custom actives ({n})")
if st.button("Retour inter 2023", key="btn_reset_inter"):
del st.session_state["custom_inter_parsed"]
if "custom_interventions" in st.session_state:
del st.session_state["custom_interventions"]
fct.unregister_custom_matrices()
st.rerun()
# --- Sidebar : Gestion des engins ---
st.sidebar.markdown("---")
st.sidebar.subheader("Gestion des engins")
if not st.session_state.allocation_dirty:
engins_current_sorted = sorted(st.session_state.engins, key=lambda e: e["id"])
engins_initial_sorted = sorted(st.session_state.engins_initial, key=lambda e: e["id"])
if engins_current_sorted != engins_initial_sorted:
st.session_state.allocation_dirty = True
if st.sidebar.button("♾️ Reset (allocation initiale)"):
st.session_state.engins = [dict(eng) for eng in st.session_state.engins_initial]
st.session_state.allocation_dirty = False
st.success("Allocation réinitialisée.")
st.rerun()
engins_base = st.session_state.engins_base
types_vhl = [("POMPE_Engin", "POMPE"), ("PSE_Engin", "PSE"), ("VSAV_Engin", "VSAV")]
for vhl_type_name, vhl_type_label in types_vhl:
count = sum(1 for e in st.session_state.engins if e.get("type") == vhl_type_name)
card = st.sidebar.container()
with card:
st.markdown(f"**{vhl_type_label} : {count}**")
# Input pour définir directement le nombre
input_cols = st.columns([3, 1])
with input_cols[0]:
new_count_str = st.text_input(
"Nombre",
value=str(count),
key=f"input_count_{vhl_type_name}",
label_visibility="collapsed",
placeholder="Nombre de véhicules"
)
# Validation du nombre
try:
new_count = int(new_count_str) if new_count_str else count
new_count = max(0, min(500, new_count)) # Limiter entre 0 et 500
except ValueError:
new_count = count
with input_cols[1]:
if st.button("✓", key=f"btn_apply_{vhl_type_name}", width='stretch'):
# Calculer la différence
diff = new_count - count
existing_ids = {e["id"] for e in st.session_state.engins}
max_id = max(existing_ids) if existing_ids else 0
if diff > 0:
# Ajouter des véhicules
for _ in range(diff):
max_id += 1
st.session_state.engins.append({
"id": max_id,
"cs": "ANTO",
"nom": f"{vhl_type_label}_{max_id}",
"type": vhl_type_name,
})
elif diff < 0:
# Retirer des véhicules
vehicles_to_remove = [e for e in st.session_state.engins if e.get("type") == vhl_type_name]
for i in range(abs(diff)):
if i < len(vehicles_to_remove):
st.session_state.engins.remove(vehicles_to_remove[i])
if diff != 0:
st.session_state.allocation_dirty = True
st.rerun()
st.sidebar.markdown("---")
# -----------------------------
# BOUTON SIMULATION (partie centrale)
# -----------------------------
st.markdown("---")
st.subheader("🚀 Lancer la simulation")
_using_custom = st.session_state.get("custom_inter_parsed", False)
_btn_label = "Simulation (custom)" if _using_custom else "Simulation (baseline)"
if st.button(f"▶️ {_btn_label}", type="primary", width='stretch'):
try:
main_module.interventions_simulees.clear()
except Exception:
pass
try:
fct.reset_stats()
progress_bar = st.progress(0)
progress_text = st.empty()
def update_progress(current, total):
progress = current / total
progress_bar.progress(progress)
progress_text.text(f"Traitement : {current}/{total} interventions ({progress*100:.1f}%)")
# Choisir les interventions : custom ou 2023
if _using_custom and "custom_interventions" in st.session_state:
interventions_filtered = st.session_state.custom_interventions
st.caption(f"Simulation sur {len(interventions_filtered)} interventions custom")
else:
sim_start = st.session_state.get("simulation_start")
sim_end = st.session_state.get("simulation_end")
interventions_filtered = st.session_state.interventions_data
if sim_start or sim_end:
interventions_filtered = [
i for i in st.session_state.interventions_data
if (sim_start is None or i.date >= sim_start)
and (sim_end is None or i.date <= sim_end)
]
# Convertir st.session_state.engins en objets Engin
engins_dict = convert_session_engins_to_objects()
# Lancer la simulation avec les données pré-chargées
main_module.main(
progress_callback=update_progress,
interventions=interventions_filtered,
indisponibilites=st.session_state.indisponibilites_data,
engins=engins_dict
)
# Finaliser la barre
progress_bar.progress(1.0)
progress_text.text("Simulation terminée !")
stats = fct.get_stats()
st.session_state.simulation_time = main_module.simulation_processing_time
st.session_state.cache_stats = stats
st.session_state.progress = 1
st.session_state.map_needs_update = True # Forcer la mise à jour de la carte
st.success(f"Simulation terminee en {main_module.simulation_processing_time:.1f}s !")
# Forcer le rafraîchissement pour afficher les nouvelles stats
st.rerun()
except Exception as e:
st.error(f"Erreur simulation: {e}")
# -----------------------------
# STAT CARD / INFO
# -----------------------------
if st.session_state.progress == 0:
st.info("Simulation non terminée")
else:
st.success("Simulation terminée")
# -----------------------------
# CARTE STATISTIQUE
# -----------------------------
# Créer la carte seulement si nécessaire (quand simulation change)
if "stat_map_html" not in st.session_state or st.session_state.get("map_needs_update", False):
stat_map = folium.Map(location=[48.8566, 2.3522], zoom_start=9)
if st.session_state.progress == 1:
def get_stat(cs):
interventions_cs = [i for i in main_module.interventions_simulees if i.cstc == cs]
if len(interventions_cs) == 0:
return datetime.timedelta(0)
total = sum([i.aller for i in interventions_cs], start=datetime.timedelta(0))
return total / len(interventions_cs)
temps = gdf["nom"].map(get_stat)
temps_min = temps.min()
temps_max = temps.max()
def style_stat(f):
cs = f["properties"]["nom"]
t = get_stat(cs).total_seconds()
min_sec = temps_min.total_seconds()
max_sec = temps_max.total_seconds()
ratio = 0 if max_sec == min_sec else (t - min_sec) / (max_sec - min_sec)
r = int(255 * ratio)
g = int(255 * (1 - ratio))
b = 0
return {
"fillColor": f"#{r:02X}{g:02X}{b:02X}",
"color": "black",
"weight": 1,
"fillOpacity": 0.6,
}
folium.GeoJson(
gdf,
style_function=style_stat,
tooltip=folium.GeoJsonTooltip(fields=["nom"], aliases=["Secteur"]),
).add_to(stat_map)
st.session_state.stat_map_html = stat_map._repr_html_()
st.session_state.map_needs_update = False
st.subheader("Carte des performances par secteur")
col_map, col_stats = st.columns([3, 1])
with col_map:
# Afficher directement le HTML au lieu de st_folium pour éviter les reruns
st.components.v1.html(st.session_state.get("stat_map_html", ""), width=700, height=500)
with col_stats:
st.markdown("### Statistiques")
if st.session_state.progress == 1:
reponses_s = [i.temps_reponse_seconds for i in main_module.interventions_simulees]
if reponses_s:
mean_reponse = float(np.mean(reponses_s))
p95_reponse = float(np.percentile(reponses_s, 95))
st.metric("Temps réponse moyen (dép+trajet)", f"{mean_reponse:.1f} s")
st.metric("P95 temps de réponse", f"{p95_reponse:.1f} s")
# Ratio de concordance CS
if hasattr(main_module, 'cs_match_count') and hasattr(main_module, 'cs_total_count'):
if main_module.cs_total_count > 0:
cs_ratio = main_module.cs_match_count / main_module.cs_total_count * 100
st.metric("Concordance CS", f"{cs_ratio:.1f}%")
st.caption(f"{main_module.cs_match_count}/{main_module.cs_total_count} CS corrects")
st.metric("Interventions", f"{len(reponses_s)}")
# Diagnostic des erreurs
if hasattr(main_module, 'cs_mismatch_details') and main_module.cs_mismatch_details:
with st.expander(f"🔍 Diagnostic ({len(main_module.cs_mismatch_details)} exemples d'erreurs)"):
import pandas as pd
df_errors = pd.DataFrame(main_module.cs_mismatch_details)
# Analyse par CS réel
st.write("**Top CS avec erreurs d'attribution:**")
cs_errors = df_errors['cs_reel'].value_counts().head(10)
st.bar_chart(cs_errors)
# Exemples détaillés
st.write("**Exemples de non-concordance:**")
st.dataframe(df_errors[['date', 'cs_reel', 'cs_attribue', 'type_vhl_envoye', 'cstc', 'fem_mma']].head(20),
width="stretch")
else:
st.info("Aucune intervention simulée.")
else:
st.info("Lancer une simulation pour voir les stats.")