Spaces:
Running on Zero
Running on Zero
Deploiement GuindiMa AI (interface Gradio) (part 2)
Browse files- data/voix_a_generer_transition.csv +2 -0
- src/intent/extract_intent.py +3 -1
- src/matching/itineraires_app.py +21 -1
- src/routing/adapter.py +48 -14
- src/routing/network.py +811 -794
- src/routing/router.py +1271 -1263
data/voix_a_generer_transition.csv
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
type,texte_a_prononcer,fichier_wav,utilise_par,statut,remarque
|
| 2 |
+
connecteur,"Soo paree,",soo_paree.wav,"app._reponse_etapes (transition entre l'étape 1 et l'étape 2)",non créé,"Option A, décision de Cheikh : seul morceau à générer. La voix dira « Soo paree, » + WAV de ligne existant (« Jëlal biis bu … ») + moo_lay_yobbu_ba.wav + lieu_<arrivée>.wav, soit exactement la phrase affichée « Soo paree, jëlal biis bu 23, moo lay yóbbu ba Parcelles. »"
|
src/intent/extract_intent.py
CHANGED
|
@@ -1339,7 +1339,9 @@ def _repli_local(transcription: str, raison: str) -> dict:
|
|
| 1339 |
# on ne l'écrit jamais telle quelle dans les logs. Le type d'échec suffit pour
|
| 1340 |
# savoir si l'API a expiré, refusé la clé ou renvoyé du JSON illisible.
|
| 1341 |
print(f"[LLM] échec {raison}, repli sur l'extraction locale", flush=True)
|
| 1342 |
-
|
|
|
|
|
|
|
| 1343 |
if resultat.get("depart") and resultat.get("arrivee"):
|
| 1344 |
return resultat
|
| 1345 |
return {**resultat, "erreur": raison}
|
|
|
|
| 1339 |
# on ne l'écrit jamais telle quelle dans les logs. Le type d'échec suffit pour
|
| 1340 |
# savoir si l'API a expiré, refusé la clé ou renvoyé du JSON illisible.
|
| 1341 |
print(f"[LLM] échec {raison}, repli sur l'extraction locale", flush=True)
|
| 1342 |
+
# Lot T2 : la cause du repli voyage avec le résultat. L'app n'affiche le
|
| 1343 |
+
# bandeau « API NVIDIA indisponible » que si un vrai appel a échoué.
|
| 1344 |
+
resultat = {**extract_local(transcription), "repli": raison}
|
| 1345 |
if resultat.get("depart") and resultat.get("arrivee"):
|
| 1346 |
return resultat
|
| 1347 |
return {**resultat, "erreur": raison}
|
src/matching/itineraires_app.py
CHANGED
|
@@ -71,6 +71,10 @@ POSITIONS_ESTIMEES = DATA / "corrections" / "positions_estimees.csv"
|
|
| 71 |
# géocodage), gardée pour mesurer la ligne mais jamais sûre ;
|
| 72 |
# - « inconnue » : aucune position (Bayakh, introuvable).
|
| 73 |
ITINERAIRES_REVUS = DATA / "corrections" / "itineraires_ddd_revus.csv"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
SOURCE_ESTIMEE = "estimee"
|
| 75 |
# Statut et terminus affichés des mêmes lignes (et de la 233) d'après les deux
|
| 76 |
# pages : « Cambérène 2 -> Palais 2 » pour la 6 alors que sa liste commence à
|
|
@@ -87,6 +91,17 @@ def nom_ligne_ddd(ligne: object) -> str:
|
|
| 87 |
return f"Ligne {texte}" if texte[:1].isdigit() else texte
|
| 88 |
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
def sans_terminus(nom: object) -> str:
|
| 91 |
"""« Terminus keur Massar » -> « Keur Massar » : le même arrêt que nos autres lignes.
|
| 92 |
|
|
@@ -233,8 +248,13 @@ def rangees_ddd_officielles(
|
|
| 233 |
if not Path(chemin).exists():
|
| 234 |
return []
|
| 235 |
ecartees = lignes_officiel_exclues(exclues)
|
|
|
|
| 236 |
rangees = [
|
| 237 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
for rangee in _lire(chemin)
|
| 239 |
]
|
| 240 |
rangees = _appliquer_itineraires_revus(rangees, revus, arrets_geo)
|
|
|
|
| 71 |
# géocodage), gardée pour mesurer la ligne mais jamais sûre ;
|
| 72 |
# - « inconnue » : aucune position (Bayakh, introuvable).
|
| 73 |
ITINERAIRES_REVUS = DATA / "corrections" / "itineraires_ddd_revus.csv"
|
| 74 |
+
# Lot T2 : noms officiels affichés autrement. « Terminus des Parcelles » (DDD 23)
|
| 75 |
+
# devenait « Des Parcelles » sans son « Terminus » ; c'est le terminus des
|
| 76 |
+
# Parcelles Assainies, celui de la DDD 1.
|
| 77 |
+
NOMS_ARRETS = DATA / "corrections" / "noms_arrets_ddd.csv"
|
| 78 |
SOURCE_ESTIMEE = "estimee"
|
| 79 |
# Statut et terminus affichés des mêmes lignes (et de la 233) d'après les deux
|
| 80 |
# pages : « Cambérène 2 -> Palais 2 » pour la 6 alors que sa liste commence à
|
|
|
|
| 91 |
return f"Ligne {texte}" if texte[:1].isdigit() else texte
|
| 92 |
|
| 93 |
|
| 94 |
+
def noms_arrets_ddd(chemin: Path = NOMS_ARRETS) -> dict[str, str]:
|
| 95 |
+
"""Nom officiel exact -> nom affiché ; vide sans fichier."""
|
| 96 |
+
if not Path(chemin).exists():
|
| 97 |
+
return {}
|
| 98 |
+
return {
|
| 99 |
+
r["nom_officiel"].strip(): r["nom_affiche"].strip()
|
| 100 |
+
for r in _lire(chemin)
|
| 101 |
+
if (r.get("nom_officiel") or "").strip() and (r.get("nom_affiche") or "").strip()
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
def sans_terminus(nom: object) -> str:
|
| 106 |
"""« Terminus keur Massar » -> « Keur Massar » : le même arrêt que nos autres lignes.
|
| 107 |
|
|
|
|
| 248 |
if not Path(chemin).exists():
|
| 249 |
return []
|
| 250 |
ecartees = lignes_officiel_exclues(exclues)
|
| 251 |
+
renommes = noms_arrets_ddd()
|
| 252 |
rangees = [
|
| 253 |
+
{
|
| 254 |
+
**rangee,
|
| 255 |
+
"ligne": nom_ligne_ddd(rangee["ligne"]),
|
| 256 |
+
"arret": renommes.get(rangee["arret"].strip()) or sans_terminus(rangee["arret"]),
|
| 257 |
+
}
|
| 258 |
for rangee in _lire(chemin)
|
| 259 |
]
|
| 260 |
rangees = _appliquer_itineraires_revus(rangees, revus, arrets_geo)
|
src/routing/adapter.py
CHANGED
|
@@ -160,17 +160,39 @@ def _bout_devine(ligne, index: int) -> bool:
|
|
| 160 |
return True
|
| 161 |
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
def duree_devinee(leg: Leg) -> bool:
|
| 164 |
"""Vrai si la durée de ce bus repose sur une longue portion sans position mesurée."""
|
| 165 |
|
| 166 |
ligne = _NETWORK.lines.get((leg.operator, leg.line))
|
| 167 |
if ligne is None:
|
| 168 |
return False
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
i, j = arrets.index(leg.board_stop), arrets.index(leg.alight_stop)
|
| 172 |
-
except ValueError:
|
| 173 |
return False
|
|
|
|
| 174 |
segments = _NETWORK._segment_distances(ligne)
|
| 175 |
trace = _NETWORK.line_distances.get(ligne.key)
|
| 176 |
if trace is not None:
|
|
@@ -212,7 +234,15 @@ def _troncon(leg: Leg) -> dict:
|
|
| 212 |
# Une boucle (Dem Dikk 502 : Gare Colobane -> Gare Colobane) a le même terminus
|
| 213 |
# aux deux bouts : seul l'ordre des arrêts peut trancher le sens.
|
| 214 |
boucle = bool(arrets) and arrets[0] == arrets[-1]
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
direct = True
|
| 217 |
ordre = arrets
|
| 218 |
elif arrets and not boucle and arrets[0] == leg.direction:
|
|
@@ -226,16 +256,20 @@ def _troncon(leg: Leg) -> dict:
|
|
| 226 |
)
|
| 227 |
ordre = arrets if direct else tuple(reversed(arrets))
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
except ValueError:
|
| 233 |
-
parcours = [leg.board_stop, leg.alight_stop]
|
| 234 |
else:
|
| 235 |
-
|
| 236 |
-
leg.board_stop
|
| 237 |
-
leg.alight_stop
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
if direct:
|
| 241 |
depart = ligne.terminus_a or (arrets[0] if arrets else "")
|
|
|
|
| 160 |
return True
|
| 161 |
|
| 162 |
|
| 163 |
+
def indices_du_troncon(leg: Leg, ligne) -> tuple[int, int] | None:
|
| 164 |
+
"""Positions de montée et de descente dans ``ligne.stops``.
|
| 165 |
+
|
| 166 |
+
Celles que le moteur a parcourues quand le tronçon les porte. Sinon (tronçon
|
| 167 |
+
fait à la main) : parmi les passages des deux arrêts, la paire la plus
|
| 168 |
+
proche. Sur une boucle, le terminus est au début ET à la fin de la liste ;
|
| 169 |
+
``.index()`` prenait toujours le premier, donc l'autre sens du tour.
|
| 170 |
+
"""
|
| 171 |
+
arrets = ligne.stops
|
| 172 |
+
i, j = leg.board_index, leg.alight_index
|
| 173 |
+
if (
|
| 174 |
+
i is not None and j is not None and 0 <= i < len(arrets) and 0 <= j < len(arrets)
|
| 175 |
+
and arrets[i] == leg.board_stop and arrets[j] == leg.alight_stop
|
| 176 |
+
):
|
| 177 |
+
return i, j
|
| 178 |
+
montees = [k for k, arret in enumerate(arrets) if arret == leg.board_stop]
|
| 179 |
+
descentes = [k for k, arret in enumerate(arrets) if arret == leg.alight_stop]
|
| 180 |
+
paires = [(a, b) for a in montees for b in descentes if a != b]
|
| 181 |
+
if not paires:
|
| 182 |
+
return None
|
| 183 |
+
return min(paires, key=lambda paire: abs(paire[1] - paire[0]))
|
| 184 |
+
|
| 185 |
+
|
| 186 |
def duree_devinee(leg: Leg) -> bool:
|
| 187 |
"""Vrai si la durée de ce bus repose sur une longue portion sans position mesurée."""
|
| 188 |
|
| 189 |
ligne = _NETWORK.lines.get((leg.operator, leg.line))
|
| 190 |
if ligne is None:
|
| 191 |
return False
|
| 192 |
+
indices = indices_du_troncon(leg, ligne)
|
| 193 |
+
if indices is None:
|
|
|
|
|
|
|
| 194 |
return False
|
| 195 |
+
i, j = indices
|
| 196 |
segments = _NETWORK._segment_distances(ligne)
|
| 197 |
trace = _NETWORK.line_distances.get(ligne.key)
|
| 198 |
if trace is not None:
|
|
|
|
| 234 |
# Une boucle (Dem Dikk 502 : Gare Colobane -> Gare Colobane) a le même terminus
|
| 235 |
# aux deux bouts : seul l'ordre des arrêts peut trancher le sens.
|
| 236 |
boucle = bool(arrets) and arrets[0] == arrets[-1]
|
| 237 |
+
indices = indices_du_troncon(leg, ligne) if boucle else None
|
| 238 |
+
if indices is not None:
|
| 239 |
+
# Boucle : les positions parcourues par le moteur donnent le sens et le
|
| 240 |
+
# tronçon exact (Médina -> Terminus Liberté 5 de la fin de liste, pas
|
| 241 |
+
# du début).
|
| 242 |
+
i, j = indices
|
| 243 |
+
direct = i <= j
|
| 244 |
+
ordre = arrets if direct else tuple(reversed(arrets))
|
| 245 |
+
elif arrets and not boucle and arrets[-1] == leg.direction:
|
| 246 |
direct = True
|
| 247 |
ordre = arrets
|
| 248 |
elif arrets and not boucle and arrets[0] == leg.direction:
|
|
|
|
| 256 |
)
|
| 257 |
ordre = arrets if direct else tuple(reversed(arrets))
|
| 258 |
|
| 259 |
+
if indices is not None:
|
| 260 |
+
i, j = indices
|
| 261 |
+
parcours = list(arrets[i:j + 1]) if i <= j else list(reversed(arrets[j:i + 1]))
|
|
|
|
|
|
|
| 262 |
else:
|
| 263 |
+
try:
|
| 264 |
+
i_dep = ordre.index(leg.board_stop)
|
| 265 |
+
i_arr = ordre.index(leg.alight_stop)
|
| 266 |
+
except ValueError:
|
| 267 |
+
parcours = [leg.board_stop, leg.alight_stop]
|
| 268 |
+
else:
|
| 269 |
+
parcours = list(ordre[i_dep : i_arr + 1]) or [
|
| 270 |
+
leg.board_stop,
|
| 271 |
+
leg.alight_stop,
|
| 272 |
+
]
|
| 273 |
|
| 274 |
if direct:
|
| 275 |
depart = ligne.terminus_a or (arrets[0] if arrets else "")
|
src/routing/network.py
CHANGED
|
@@ -1,794 +1,811 @@
|
|
| 1 |
-
"""The Dakar bus graph.
|
| 2 |
-
|
| 3 |
-
A node is a stop **as seen by one line in one direction**. Keeping the
|
| 4 |
-
direction in the node is what lets the router produce a proper leg with a
|
| 5 |
-
terminus ("towards Palais 2") instead of just a pair of stop names.
|
| 6 |
-
|
| 7 |
-
Each line is usable in both directions. Ride edges follow the ordered
|
| 8 |
-
itinerary; transfer edges connect different lines at the same normalized
|
| 9 |
-
stop name, or at two stops within 500 m.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
from __future__ import annotations
|
| 13 |
-
|
| 14 |
-
import heapq
|
| 15 |
-
import math
|
| 16 |
-
from collections import Counter, defaultdict
|
| 17 |
-
from dataclasses import dataclass
|
| 18 |
-
from typing import Iterable, NamedTuple
|
| 19 |
-
|
| 20 |
-
from .places import _GENERIC_TOKENS, normalize_name, terminus_forms
|
| 21 |
-
from .traces import distances_sur_trace
|
| 22 |
-
|
| 23 |
-
# Modeling constants. They are deliberately simple and easy to tune.
|
| 24 |
-
# Vitesse commerciale, sur de vraies longueurs de route. Sur le terrain, les bus
|
| 25 |
-
# Dem Dikk roulent nettement plus vite que les Tata, qui s'arrêtent partout.
|
| 26 |
-
SPEED_BY_COMPANY_M_PER_MIN = {
|
| 27 |
-
"Dakar Dem Dikk": 333.0, # 20 km/h
|
| 28 |
-
"Tata AFTU": 250.0, # 15 km/h
|
| 29 |
-
}
|
| 30 |
-
# La plus rapide : la recherche guidée s'en sert pour ne jamais surestimer le
|
| 31 |
-
# temps restant. Une compagnie inconnue roule à cette vitesse aussi.
|
| 32 |
-
BUS_SPEED_M_PER_MIN = max(SPEED_BY_COMPANY_M_PER_MIN.values())
|
| 33 |
-
FIXED_MINUTES_PER_SEGMENT = 3.0 # fallback when a stop has no coordinates
|
| 34 |
-
# Une ligne réduite à ses deux terminus, dont l'un sans position, n'a aucun
|
| 35 |
-
# arrêt pour borner la distance : Dem Dikk 11 (Keur Massar -> Lat Dior) coûtait
|
| 36 |
-
# 3 min et devenait une téléportation à travers toute la ville.
|
| 37 |
-
UNKNOWN_TWO_STOP_RIDE_MINUTES = 35.0
|
| 38 |
-
TRANSFER_PENALTY_MIN = 6.0 # waiting / walking to the next line
|
| 39 |
-
WALK_SPEED_M_PER_MIN = 80.0
|
| 40 |
-
# Une correspondance à pied ne dépasse pas 400 m (5 min) : au-delà, l'usager
|
| 41 |
-
# ne retrouve plus l'arrêt du bus suivant sans aide.
|
| 42 |
-
MAX_TRANSFER_WALK_M = 400.0
|
| 43 |
-
# Correspondances à pied gardées pour deux lignes données : les plus courtes. Toutes
|
| 44 |
-
# les garder faisait 126 000 arêtes et jusqu'à 44 s par requête, sans bus direct.
|
| 45 |
-
MAX_WALK_TRANSFERS_PER_LINE_PAIR = 2
|
| 46 |
-
# Un ancien nom absent des listes officielles (« Cambérène 2 ») vaut l'arrêt officiel
|
| 47 |
-
# le plus proche : portant le même nom de quartier, ou tout près s'il n'y en a pas.
|
| 48 |
-
LEGACY_SAME_NAME_RADIUS_M = 2_000.0
|
| 49 |
-
LEGACY_ANY_NAME_RADIUS_M = 500.0
|
| 50 |
-
POSITION_AGREEMENT_M = 500.0
|
| 51 |
-
SAME_NAME_MAX_APART_M = 1_000.0
|
| 52 |
-
|
| 53 |
-
LineKey = tuple[str, str] # (operator, line name)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
class Node(NamedTuple):
|
| 57 |
-
line: LineKey
|
| 58 |
-
direction: int # 0 = itinerary order, 1 = reversed
|
| 59 |
-
index: int
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
@dataclass(frozen=True)
|
| 63 |
-
class Line:
|
| 64 |
-
company: str
|
| 65 |
-
name: str
|
| 66 |
-
stops: tuple[str, ...]
|
| 67 |
-
terminus_a: str | None = None
|
| 68 |
-
terminus_b: str | None = None
|
| 69 |
-
|
| 70 |
-
@property
|
| 71 |
-
def key(self) -> LineKey:
|
| 72 |
-
return (self.company, self.name)
|
| 73 |
-
|
| 74 |
-
def stops_for(self, direction: int) -> tuple[str, ...]:
|
| 75 |
-
return self.stops if direction == 0 else tuple(reversed(self.stops))
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
return
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def
|
| 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 |
-
for stop
|
| 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 |
-
self.
|
| 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 |
-
self.
|
| 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 |
-
for index in range(
|
| 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 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
)
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
)
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
if
|
| 691 |
-
continue
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
#
|
| 762 |
-
#
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The Dakar bus graph.
|
| 2 |
+
|
| 3 |
+
A node is a stop **as seen by one line in one direction**. Keeping the
|
| 4 |
+
direction in the node is what lets the router produce a proper leg with a
|
| 5 |
+
terminus ("towards Palais 2") instead of just a pair of stop names.
|
| 6 |
+
|
| 7 |
+
Each line is usable in both directions. Ride edges follow the ordered
|
| 8 |
+
itinerary; transfer edges connect different lines at the same normalized
|
| 9 |
+
stop name, or at two stops within 500 m.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import heapq
|
| 15 |
+
import math
|
| 16 |
+
from collections import Counter, defaultdict
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Iterable, NamedTuple
|
| 19 |
+
|
| 20 |
+
from .places import _GENERIC_TOKENS, normalize_name, terminus_forms
|
| 21 |
+
from .traces import distances_sur_trace
|
| 22 |
+
|
| 23 |
+
# Modeling constants. They are deliberately simple and easy to tune.
|
| 24 |
+
# Vitesse commerciale, sur de vraies longueurs de route. Sur le terrain, les bus
|
| 25 |
+
# Dem Dikk roulent nettement plus vite que les Tata, qui s'arrêtent partout.
|
| 26 |
+
SPEED_BY_COMPANY_M_PER_MIN = {
|
| 27 |
+
"Dakar Dem Dikk": 333.0, # 20 km/h
|
| 28 |
+
"Tata AFTU": 250.0, # 15 km/h
|
| 29 |
+
}
|
| 30 |
+
# La plus rapide : la recherche guidée s'en sert pour ne jamais surestimer le
|
| 31 |
+
# temps restant. Une compagnie inconnue roule à cette vitesse aussi.
|
| 32 |
+
BUS_SPEED_M_PER_MIN = max(SPEED_BY_COMPANY_M_PER_MIN.values())
|
| 33 |
+
FIXED_MINUTES_PER_SEGMENT = 3.0 # fallback when a stop has no coordinates
|
| 34 |
+
# Une ligne réduite à ses deux terminus, dont l'un sans position, n'a aucun
|
| 35 |
+
# arrêt pour borner la distance : Dem Dikk 11 (Keur Massar -> Lat Dior) coûtait
|
| 36 |
+
# 3 min et devenait une téléportation à travers toute la ville.
|
| 37 |
+
UNKNOWN_TWO_STOP_RIDE_MINUTES = 35.0
|
| 38 |
+
TRANSFER_PENALTY_MIN = 6.0 # waiting / walking to the next line
|
| 39 |
+
WALK_SPEED_M_PER_MIN = 80.0
|
| 40 |
+
# Une correspondance à pied ne dépasse pas 400 m (5 min) : au-delà, l'usager
|
| 41 |
+
# ne retrouve plus l'arrêt du bus suivant sans aide.
|
| 42 |
+
MAX_TRANSFER_WALK_M = 400.0
|
| 43 |
+
# Correspondances à pied gardées pour deux lignes données : les plus courtes. Toutes
|
| 44 |
+
# les garder faisait 126 000 arêtes et jusqu'à 44 s par requête, sans bus direct.
|
| 45 |
+
MAX_WALK_TRANSFERS_PER_LINE_PAIR = 2
|
| 46 |
+
# Un ancien nom absent des listes officielles (« Cambérène 2 ») vaut l'arrêt officiel
|
| 47 |
+
# le plus proche : portant le même nom de quartier, ou tout près s'il n'y en a pas.
|
| 48 |
+
LEGACY_SAME_NAME_RADIUS_M = 2_000.0
|
| 49 |
+
LEGACY_ANY_NAME_RADIUS_M = 500.0
|
| 50 |
+
POSITION_AGREEMENT_M = 500.0
|
| 51 |
+
SAME_NAME_MAX_APART_M = 1_000.0
|
| 52 |
+
|
| 53 |
+
LineKey = tuple[str, str] # (operator, line name)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Node(NamedTuple):
|
| 57 |
+
line: LineKey
|
| 58 |
+
direction: int # 0 = itinerary order, 1 = reversed
|
| 59 |
+
index: int
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclass(frozen=True)
|
| 63 |
+
class Line:
|
| 64 |
+
company: str
|
| 65 |
+
name: str
|
| 66 |
+
stops: tuple[str, ...]
|
| 67 |
+
terminus_a: str | None = None
|
| 68 |
+
terminus_b: str | None = None
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def key(self) -> LineKey:
|
| 72 |
+
return (self.company, self.name)
|
| 73 |
+
|
| 74 |
+
def stops_for(self, direction: int) -> tuple[str, ...]:
|
| 75 |
+
return self.stops if direction == 0 else tuple(reversed(self.stops))
|
| 76 |
+
|
| 77 |
+
@property
|
| 78 |
+
def is_loop(self) -> bool:
|
| 79 |
+
"""Même terminus au début et à la fin : une boucle à sens unique."""
|
| 80 |
+
return len(self.stops) > 2 and self.stops[0] == self.stops[-1]
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def directions(self) -> tuple[int, ...]:
|
| 84 |
+
"""Les sens où le bus roule. Une boucle (Dem Dikk 18 et 20, miroirs
|
| 85 |
+
l'une de l'autre) ne roule que dans l'ordre de sa liste : la parcourir à
|
| 86 |
+
l'envers faisait passer la 20 par Fann pour aller de Médina à Dieuppeul,
|
| 87 |
+
le chemin de la 18."""
|
| 88 |
+
return (0,) if self.is_loop else (0, 1)
|
| 89 |
+
|
| 90 |
+
def terminus_for(self, direction: int) -> str:
|
| 91 |
+
return self.stops_for(direction)[-1]
|
| 92 |
+
|
| 93 |
+
def index_in_list(self, direction: int, index: int) -> int:
|
| 94 |
+
"""Position dans ``stops`` d'un index donné dans le sens ``direction``."""
|
| 95 |
+
return index if direction == 0 else len(self.stops) - 1 - index
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@dataclass(frozen=True)
|
| 99 |
+
class Edge:
|
| 100 |
+
target: Node
|
| 101 |
+
kind: str # "ride" or "transfer"
|
| 102 |
+
minutes: float
|
| 103 |
+
distance_m: float | None = None
|
| 104 |
+
walk_minutes: float = 0.0
|
| 105 |
+
walk_distance_m: float | None = None
|
| 106 |
+
transfer_penalty: float = 0.0
|
| 107 |
+
estimated: bool = False # durée forfaitaire, pas de distance connue
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _number(value: object) -> float | None:
|
| 111 |
+
"""Convert a CSV value to a coordinate, or None when it is missing."""
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
number = float(value)
|
| 115 |
+
except (TypeError, ValueError):
|
| 116 |
+
return None
|
| 117 |
+
return None if math.isnan(number) else number
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def haversine_m(
|
| 121 |
+
a: tuple[float, float],
|
| 122 |
+
b: tuple[float, float],
|
| 123 |
+
) -> float:
|
| 124 |
+
"""Great-circle distance in metres."""
|
| 125 |
+
|
| 126 |
+
lat1, lon1 = map(math.radians, a)
|
| 127 |
+
lat2, lon2 = map(math.radians, b)
|
| 128 |
+
dlat = lat2 - lat1
|
| 129 |
+
dlon = lon2 - lon1
|
| 130 |
+
h = (
|
| 131 |
+
math.sin(dlat / 2) ** 2
|
| 132 |
+
+ math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
|
| 133 |
+
)
|
| 134 |
+
return 2 * 6_371_000 * math.asin(math.sqrt(h))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def interpolate_missing_coordinates(
|
| 138 |
+
lines: Iterable[Line],
|
| 139 |
+
stop_coords: dict[str, tuple[float, float]],
|
| 140 |
+
stop_confidence: dict[str, str] | None = None,
|
| 141 |
+
passes: int = 3,
|
| 142 |
+
) -> tuple[dict[str, tuple[float, float]], dict[str, str]]:
|
| 143 |
+
"""Place unlocated stops between the located stops around them.
|
| 144 |
+
|
| 145 |
+
L'arrêt prend la position linéaire entre l'arrêt géolocalisé qui le
|
| 146 |
+
précède et celui qui le suit sur la ligne. Si plusieurs lignes le
|
| 147 |
+
desservent, on moyenne leurs propositions. Les trois passes permettent
|
| 148 |
+
à un arrêt interpolé sur une ligne de servir d'ancre sur une autre.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
coords = dict(stop_coords)
|
| 152 |
+
confidence = dict(stop_confidence or {})
|
| 153 |
+
|
| 154 |
+
for _ in range(max(1, passes)):
|
| 155 |
+
proposals: dict[str, list[tuple[float, float]]] = defaultdict(list)
|
| 156 |
+
for line in lines:
|
| 157 |
+
stops = line.stops
|
| 158 |
+
for index, stop in enumerate(stops):
|
| 159 |
+
if stop in coords:
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
previous = None
|
| 163 |
+
for before in range(index - 1, -1, -1):
|
| 164 |
+
if stops[before] in coords:
|
| 165 |
+
previous = before
|
| 166 |
+
break
|
| 167 |
+
following = None
|
| 168 |
+
for after in range(index + 1, len(stops)):
|
| 169 |
+
if stops[after] in coords:
|
| 170 |
+
following = after
|
| 171 |
+
break
|
| 172 |
+
if previous is None or following is None:
|
| 173 |
+
continue
|
| 174 |
+
|
| 175 |
+
ratio = (index - previous) / (following - previous)
|
| 176 |
+
start = coords[stops[previous]]
|
| 177 |
+
end = coords[stops[following]]
|
| 178 |
+
proposals[stop].append(
|
| 179 |
+
(
|
| 180 |
+
start[0] + (end[0] - start[0]) * ratio,
|
| 181 |
+
start[1] + (end[1] - start[1]) * ratio,
|
| 182 |
+
)
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
if not proposals:
|
| 186 |
+
break
|
| 187 |
+
for stop, points in proposals.items():
|
| 188 |
+
if stop in coords:
|
| 189 |
+
continue
|
| 190 |
+
coords[stop] = (
|
| 191 |
+
sum(point[0] for point in points) / len(points),
|
| 192 |
+
sum(point[1] for point in points) / len(points),
|
| 193 |
+
)
|
| 194 |
+
confidence[stop] = "interpolee"
|
| 195 |
+
|
| 196 |
+
return coords, confidence
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _name_tokens(name: str) -> set[str]:
|
| 200 |
+
return {
|
| 201 |
+
token
|
| 202 |
+
for token in normalize_name(name).split()
|
| 203 |
+
if token not in _GENERIC_TOKENS and not token.isdigit()
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _legacy_stops(
|
| 208 |
+
data,
|
| 209 |
+
lines: list[Line],
|
| 210 |
+
stop_coords: dict[str, tuple[float, float]],
|
| 211 |
+
stop_confidence: dict[str, str],
|
| 212 |
+
) -> dict[str, str]:
|
| 213 |
+
"""Ancien nom bien situé -> arrêt officiel le plus proche de la même zone.
|
| 214 |
+
|
| 215 |
+
Une position interpolée ne désigne jamais de zone, ni un ancien nom douteux :
|
| 216 |
+
mieux vaut ne pas répondre que répondre à côté.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
current = {stop for line in lines for stop in line.stops}
|
| 220 |
+
norms = {normalize_name(stop) for stop in current}
|
| 221 |
+
located = [
|
| 222 |
+
(stop, stop_coords[stop], _name_tokens(stop))
|
| 223 |
+
for stop in current
|
| 224 |
+
if stop in stop_coords and stop_confidence.get(stop) in {"bonne", "estimee"}
|
| 225 |
+
]
|
| 226 |
+
|
| 227 |
+
legacy: dict[str, str] = {}
|
| 228 |
+
for row in data.arrets.itertuples(index=False):
|
| 229 |
+
name = str(row.arret)
|
| 230 |
+
if (
|
| 231 |
+
normalize_name(name) in norms
|
| 232 |
+
or getattr(row, "confiance", None) != "bonne"
|
| 233 |
+
):
|
| 234 |
+
continue
|
| 235 |
+
lat, lon = _number(row.lat), _number(row.lon)
|
| 236 |
+
if lat is None or lon is None:
|
| 237 |
+
continue
|
| 238 |
+
tokens = _name_tokens(name)
|
| 239 |
+
best: tuple[bool, float, str] | None = None
|
| 240 |
+
for stop, coords, stop_tokens in located:
|
| 241 |
+
distance = haversine_m((lat, lon), coords)
|
| 242 |
+
same_area = bool(tokens & stop_tokens)
|
| 243 |
+
limit = (
|
| 244 |
+
LEGACY_SAME_NAME_RADIUS_M if same_area else LEGACY_ANY_NAME_RADIUS_M
|
| 245 |
+
)
|
| 246 |
+
if distance > limit:
|
| 247 |
+
continue
|
| 248 |
+
candidate = (not same_area, distance, stop)
|
| 249 |
+
if best is None or candidate < best:
|
| 250 |
+
best = candidate
|
| 251 |
+
if best is not None:
|
| 252 |
+
legacy[name] = best[2]
|
| 253 |
+
return legacy
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class Network:
|
| 257 |
+
def __init__(
|
| 258 |
+
self,
|
| 259 |
+
lines: Iterable[Line],
|
| 260 |
+
stop_coords: dict[str, tuple[float, float]],
|
| 261 |
+
stop_confidence: dict[str, str] | None = None,
|
| 262 |
+
line_positions: dict[LineKey, tuple] | None = None,
|
| 263 |
+
line_distances: dict[LineKey, tuple] | None = None,
|
| 264 |
+
legacy_stops: dict[str, str] | None = None,
|
| 265 |
+
line_sure: dict[LineKey, tuple] | None = None,
|
| 266 |
+
) -> None:
|
| 267 |
+
self.lines = {line.key: line for line in lines}
|
| 268 |
+
self.stop_coords = dict(stop_coords)
|
| 269 |
+
self.stop_confidence = dict(stop_confidence or {})
|
| 270 |
+
# Position de chaque arrêt sur sa ligne, et longueur mesurée sur la trace.
|
| 271 |
+
self.line_positions = dict(line_positions or {})
|
| 272 |
+
self.line_distances = dict(line_distances or {})
|
| 273 |
+
# Position mesurée (arrêt OSM, terminus officiel…) ou devinée
|
| 274 |
+
# (interpolation le long de la ligne) : seule la première peut porter
|
| 275 |
+
# une correspondance à pied ou borner une durée.
|
| 276 |
+
self.line_sure = dict(line_sure or {})
|
| 277 |
+
self.stop_names = sorted(
|
| 278 |
+
{stop for line in self.lines.values() for stop in line.stops}
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
self._nodes_at_stop: dict[str, list[Node]] = defaultdict(list)
|
| 282 |
+
self._nodes_at_norm: dict[str, list[Node]] = defaultdict(list)
|
| 283 |
+
self._stops_by_norm: dict[str, list[str]] = defaultdict(list)
|
| 284 |
+
self._all_nodes: list[Node] = []
|
| 285 |
+
|
| 286 |
+
for line in self.lines.values():
|
| 287 |
+
for direction in line.directions:
|
| 288 |
+
sequence = line.stops_for(direction)
|
| 289 |
+
for index, stop in enumerate(sequence):
|
| 290 |
+
node = Node(line.key, direction, index)
|
| 291 |
+
self._all_nodes.append(node)
|
| 292 |
+
self._nodes_at_stop[stop].append(node)
|
| 293 |
+
self._nodes_at_norm[normalize_name(stop)].append(node)
|
| 294 |
+
|
| 295 |
+
for stop in self.stop_names:
|
| 296 |
+
self._stops_by_norm[normalize_name(stop)].append(stop)
|
| 297 |
+
|
| 298 |
+
# « Dieuppeul » et « Liberté 5 » mènent aussi à « Terminus liberté 5
|
| 299 |
+
# (Dieuppeul) », sans en faire le même arrêt pour les correspondances.
|
| 300 |
+
for stop in self.stop_names:
|
| 301 |
+
for form in terminus_forms(stop):
|
| 302 |
+
names = self._stops_by_norm[normalize_name(form)]
|
| 303 |
+
if stop not in names:
|
| 304 |
+
names.append(stop)
|
| 305 |
+
for old_name, stop in (legacy_stops or {}).items():
|
| 306 |
+
normalized = normalize_name(old_name)
|
| 307 |
+
if not self._stops_by_norm.get(normalized):
|
| 308 |
+
self._stops_by_norm[normalized] = [stop]
|
| 309 |
+
|
| 310 |
+
self._adjacency: dict[Node, list[Edge]] | None = None
|
| 311 |
+
|
| 312 |
+
# ------------------------------------------------------------------
|
| 313 |
+
# Small accessors used by the router and the CLI.
|
| 314 |
+
# ------------------------------------------------------------------
|
| 315 |
+
@property
|
| 316 |
+
def all_nodes(self) -> list[Node]:
|
| 317 |
+
return self._all_nodes
|
| 318 |
+
|
| 319 |
+
def line_for(self, node: Node) -> Line:
|
| 320 |
+
return self.lines[node.line]
|
| 321 |
+
|
| 322 |
+
def stop_for(self, node: Node) -> str:
|
| 323 |
+
return self.line_for(node).stops_for(node.direction)[node.index]
|
| 324 |
+
|
| 325 |
+
def terminus_for(self, node: Node) -> str:
|
| 326 |
+
return self.line_for(node).terminus_for(node.direction)
|
| 327 |
+
|
| 328 |
+
def nodes_at_stop(self, stop: str) -> list[Node]:
|
| 329 |
+
return self._nodes_at_stop.get(stop, [])
|
| 330 |
+
|
| 331 |
+
def nodes_at_normalized(self, normalized: str) -> list[Node]:
|
| 332 |
+
return self._nodes_at_norm.get(normalized, [])
|
| 333 |
+
|
| 334 |
+
def stops_for_normalized(self, normalized: str) -> list[str]:
|
| 335 |
+
return list(self._stops_by_norm.get(normalized, ()))
|
| 336 |
+
|
| 337 |
+
def coords(self, stop: str) -> tuple[float, float] | None:
|
| 338 |
+
return self.stop_coords.get(stop)
|
| 339 |
+
|
| 340 |
+
@property
|
| 341 |
+
def downtown_centre(self) -> tuple[float, float] | None:
|
| 342 |
+
"""Approximate the city centre with the Palais stops."""
|
| 343 |
+
|
| 344 |
+
points = [
|
| 345 |
+
self.stop_coords[name]
|
| 346 |
+
for name in ("Palais 1", "Palais 2", "Palais")
|
| 347 |
+
if name in self.stop_coords
|
| 348 |
+
]
|
| 349 |
+
if not points:
|
| 350 |
+
return None
|
| 351 |
+
return (
|
| 352 |
+
sum(point[0] for point in points) / len(points),
|
| 353 |
+
sum(point[1] for point in points) / len(points),
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# ------------------------------------------------------------------
|
| 357 |
+
# Graph construction.
|
| 358 |
+
# ------------------------------------------------------------------
|
| 359 |
+
@property
|
| 360 |
+
def adjacency(self) -> dict[Node, list[Edge]]:
|
| 361 |
+
if self._adjacency is None:
|
| 362 |
+
self._adjacency = self._build_adjacency()
|
| 363 |
+
return self._adjacency
|
| 364 |
+
|
| 365 |
+
def position_on_line(self, line: Line, index: int) -> tuple[float, float] | None:
|
| 366 |
+
"""La position de cet arrêt sur cette ligne (sa position générale par défaut)."""
|
| 367 |
+
|
| 368 |
+
positions = self.line_positions.get(line.key)
|
| 369 |
+
if positions is not None:
|
| 370 |
+
return positions[index]
|
| 371 |
+
return self.coords(line.stops[index])
|
| 372 |
+
|
| 373 |
+
def position_sure(self, line: Line, index: int) -> bool:
|
| 374 |
+
"""Vrai si la position de cet arrêt sur cette ligne est mesurée, pas devinée.
|
| 375 |
+
|
| 376 |
+
« Marché Colobane Rufisque » (Tata 57), placé par interpolation sur
|
| 377 |
+
ZAC Mbao, faisait changer de bus « à 1 min à pied » de ZAC Mbao.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
drapeaux = self.line_sure.get(line.key)
|
| 381 |
+
if drapeaux is not None:
|
| 382 |
+
return bool(drapeaux[index])
|
| 383 |
+
return self.stop_confidence.get(line.stops[index]) == "bonne"
|
| 384 |
+
|
| 385 |
+
def _plancher_vol_oiseau(
|
| 386 |
+
self, line: Line, segments: tuple[float | None, ...]
|
| 387 |
+
) -> tuple[float | None, ...]:
|
| 388 |
+
"""Une route n'est jamais plus courte que la ligne droite.
|
| 389 |
+
|
| 390 |
+
Entre deux arrêts aux positions sûres, la somme des segments est au
|
| 391 |
+
moins la distance à vol d'oiseau ; sinon les segments sont allongés
|
| 392 |
+
d'autant. Une trace projetée sur des arrêts mal placés donnait
|
| 393 |
+
« Route Nationale N°1 -> Marché Colobane Rufisque » en 7 min.
|
| 394 |
+
"""
|
| 395 |
+
|
| 396 |
+
surs = [
|
| 397 |
+
index
|
| 398 |
+
for index in range(len(line.stops))
|
| 399 |
+
if self.position_sure(line, index)
|
| 400 |
+
and self.position_on_line(line, index) is not None
|
| 401 |
+
]
|
| 402 |
+
resultat = list(segments)
|
| 403 |
+
for gauche, droite in zip(surs, surs[1:]):
|
| 404 |
+
morceau = resultat[gauche:droite]
|
| 405 |
+
if any(valeur is None for valeur in morceau):
|
| 406 |
+
continue
|
| 407 |
+
longueur = sum(morceau)
|
| 408 |
+
droite_m = haversine_m(
|
| 409 |
+
self.position_on_line(line, gauche),
|
| 410 |
+
self.position_on_line(line, droite),
|
| 411 |
+
)
|
| 412 |
+
if longueur <= 0 or longueur >= droite_m:
|
| 413 |
+
continue
|
| 414 |
+
facteur = droite_m / longueur
|
| 415 |
+
for index in range(gauche, droite):
|
| 416 |
+
resultat[index] = resultat[index] * facteur
|
| 417 |
+
return tuple(resultat)
|
| 418 |
+
|
| 419 |
+
def _segment_distances(self, line: Line) -> tuple[float | None, ...]:
|
| 420 |
+
"""Longueur de chaque segment, dans l'ordre de la ligne.
|
| 421 |
+
|
| 422 |
+
La trace d'abord, sinon les distances entre arrêts consécutifs. Un arrêt
|
| 423 |
+
sans position est sauté : la distance entre ses deux voisins est partagée.
|
| 424 |
+
"""
|
| 425 |
+
|
| 426 |
+
mesurees = self.line_distances.get(line.key)
|
| 427 |
+
if mesurees is not None:
|
| 428 |
+
return self._plancher_vol_oiseau(line, mesurees)
|
| 429 |
+
|
| 430 |
+
positions = [
|
| 431 |
+
self.position_on_line(line, index) for index in range(len(line.stops))
|
| 432 |
+
]
|
| 433 |
+
connus = [i for i, position in enumerate(positions) if position is not None]
|
| 434 |
+
segments: list[float | None] = [None] * (len(positions) - 1)
|
| 435 |
+
for gauche, droite in zip(connus, connus[1:]):
|
| 436 |
+
part = haversine_m(positions[gauche], positions[droite]) / (droite - gauche)
|
| 437 |
+
for index in range(gauche, droite):
|
| 438 |
+
segments[index] = part
|
| 439 |
+
return self._plancher_vol_oiseau(line, tuple(segments))
|
| 440 |
+
|
| 441 |
+
@staticmethod
|
| 442 |
+
def _ride_estimate(
|
| 443 |
+
distance: float | None,
|
| 444 |
+
stops_on_line: int,
|
| 445 |
+
company: str = "",
|
| 446 |
+
) -> float:
|
| 447 |
+
if distance is None:
|
| 448 |
+
if stops_on_line == 2:
|
| 449 |
+
return UNKNOWN_TWO_STOP_RIDE_MINUTES
|
| 450 |
+
return FIXED_MINUTES_PER_SEGMENT
|
| 451 |
+
speed = SPEED_BY_COMPANY_M_PER_MIN.get(company, BUS_SPEED_M_PER_MIN)
|
| 452 |
+
return max(0.5, distance / speed)
|
| 453 |
+
|
| 454 |
+
def _build_adjacency(self) -> dict[Node, list[Edge]]:
|
| 455 |
+
adjacency: dict[Node, list[Edge]] = {
|
| 456 |
+
node: [] for node in self._all_nodes
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
# Ride along the ordered stops, in both directions.
|
| 460 |
+
for line in self.lines.values():
|
| 461 |
+
forward = self._segment_distances(line)
|
| 462 |
+
for direction in line.directions:
|
| 463 |
+
sequence = line.stops_for(direction)
|
| 464 |
+
distances = forward if direction == 0 else forward[::-1]
|
| 465 |
+
for index in range(len(sequence) - 1):
|
| 466 |
+
source = Node(line.key, direction, index)
|
| 467 |
+
target = Node(line.key, direction, index + 1)
|
| 468 |
+
distance = distances[index]
|
| 469 |
+
minutes = self._ride_estimate(
|
| 470 |
+
distance, len(sequence), line.company
|
| 471 |
+
)
|
| 472 |
+
adjacency[source].append(
|
| 473 |
+
Edge(
|
| 474 |
+
target=target,
|
| 475 |
+
kind="ride",
|
| 476 |
+
minutes=minutes,
|
| 477 |
+
distance_m=distance,
|
| 478 |
+
estimated=distance is None and len(sequence) == 2,
|
| 479 |
+
)
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
# Transfers at the same normalized stop name. This also joins
|
| 483 |
+
# spellings such as "Sahm" and "SAHM".
|
| 484 |
+
# Deux lignes peuvent donner le même nom à deux endroits éloignés : « VDN » est
|
| 485 |
+
# une avenue de 15 km, et Tata 37 y passe loin de TAF TAF. Sans ce contrôle,
|
| 486 |
+
# on changeait de bus à « VDN » en se téléportant vers Malika.
|
| 487 |
+
def node_position(node: Node) -> tuple[float, float] | None:
|
| 488 |
+
line = self.lines[node.line]
|
| 489 |
+
index = (
|
| 490 |
+
node.index
|
| 491 |
+
if node.direction == 0
|
| 492 |
+
else len(line.stops) - 1 - node.index
|
| 493 |
+
)
|
| 494 |
+
return self.position_on_line(line, index)
|
| 495 |
+
|
| 496 |
+
for nodes in self._nodes_at_norm.values():
|
| 497 |
+
positions = {node: node_position(node) for node in nodes}
|
| 498 |
+
for source in nodes:
|
| 499 |
+
for target in nodes:
|
| 500 |
+
if source == target or source.line == target.line:
|
| 501 |
+
continue
|
| 502 |
+
here, there = positions[source], positions[target]
|
| 503 |
+
if (
|
| 504 |
+
here is not None
|
| 505 |
+
and there is not None
|
| 506 |
+
and haversine_m(here, there) > SAME_NAME_MAX_APART_M
|
| 507 |
+
):
|
| 508 |
+
continue
|
| 509 |
+
adjacency[source].append(
|
| 510 |
+
Edge(
|
| 511 |
+
target=target,
|
| 512 |
+
kind="transfer",
|
| 513 |
+
minutes=TRANSFER_PENALTY_MIN,
|
| 514 |
+
walk_minutes=0.0,
|
| 515 |
+
walk_distance_m=0.0,
|
| 516 |
+
transfer_penalty=TRANSFER_PENALTY_MIN,
|
| 517 |
+
)
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
# Short walking transfers between different stop names: only the closest
|
| 521 |
+
# stop pairs of each pair of lines.
|
| 522 |
+
lines_at_stop: dict[str, set[LineKey]] = defaultdict(set)
|
| 523 |
+
nodes_on_line: dict[tuple[LineKey, str], list[Node]] = defaultdict(list)
|
| 524 |
+
for stop, nodes in self._nodes_at_stop.items():
|
| 525 |
+
for node in nodes:
|
| 526 |
+
lines_at_stop[stop].add(node.line)
|
| 527 |
+
nodes_on_line[(node.line, stop)].append(node)
|
| 528 |
+
|
| 529 |
+
def position_for(line: LineKey, stop: str) -> tuple[float, float] | None:
|
| 530 |
+
first = min(
|
| 531 |
+
(node for node in nodes_on_line[(line, stop)] if node.direction == 0),
|
| 532 |
+
key=lambda node: node.index,
|
| 533 |
+
)
|
| 534 |
+
# Une position devinée ne fait jamais marcher l'usager : « péage »
|
| 535 |
+
# (Dem Dikk 213), interpolé entre Poste Thiaroye et Patte d'Oie,
|
| 536 |
+
# tombait « à 1 min » de Bountou Pikine.
|
| 537 |
+
if not self.position_sure(self.lines[line], first.index):
|
| 538 |
+
return None
|
| 539 |
+
return self.position_on_line(self.lines[line], first.index)
|
| 540 |
+
|
| 541 |
+
by_line_pair: dict[
|
| 542 |
+
tuple[LineKey, LineKey], list[tuple[float, str, str]]
|
| 543 |
+
] = defaultdict(list)
|
| 544 |
+
stops_with_coords = [
|
| 545 |
+
stop for stop in self.stop_names if stop in self.stop_coords
|
| 546 |
+
]
|
| 547 |
+
for left_index, left_stop in enumerate(stops_with_coords):
|
| 548 |
+
left_norm = normalize_name(left_stop)
|
| 549 |
+
for right_stop in stops_with_coords[left_index + 1 :]:
|
| 550 |
+
if normalize_name(right_stop) == left_norm:
|
| 551 |
+
continue
|
| 552 |
+
distance = haversine_m(
|
| 553 |
+
self.stop_coords[left_stop], self.stop_coords[right_stop]
|
| 554 |
+
)
|
| 555 |
+
if distance > MAX_TRANSFER_WALK_M:
|
| 556 |
+
continue
|
| 557 |
+
for left_line in lines_at_stop[left_stop]:
|
| 558 |
+
for right_line in lines_at_stop[right_stop]:
|
| 559 |
+
# Là où chaque ligne passe vraiment : une position générale
|
| 560 |
+
# fausse mettait Pikine Texaco (Tata 80) à côté de Ngor.
|
| 561 |
+
left_here = position_for(left_line, left_stop)
|
| 562 |
+
right_here = position_for(right_line, right_stop)
|
| 563 |
+
if (
|
| 564 |
+
left_here is None
|
| 565 |
+
or right_here is None
|
| 566 |
+
or haversine_m(left_here, right_here) > MAX_TRANSFER_WALK_M
|
| 567 |
+
):
|
| 568 |
+
continue
|
| 569 |
+
if left_line < right_line:
|
| 570 |
+
by_line_pair[(left_line, right_line)].append(
|
| 571 |
+
(distance, left_stop, right_stop)
|
| 572 |
+
)
|
| 573 |
+
elif right_line < left_line:
|
| 574 |
+
by_line_pair[(right_line, left_line)].append(
|
| 575 |
+
(distance, right_stop, left_stop)
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
for (first_line, second_line), candidates in by_line_pair.items():
|
| 579 |
+
closest = heapq.nsmallest(MAX_WALK_TRANSFERS_PER_LINE_PAIR, candidates)
|
| 580 |
+
for distance, first_stop, second_stop in closest:
|
| 581 |
+
walk_minutes = distance / WALK_SPEED_M_PER_MIN
|
| 582 |
+
cost = TRANSFER_PENALTY_MIN + walk_minutes
|
| 583 |
+
for source in nodes_on_line[(first_line, first_stop)]:
|
| 584 |
+
for target in nodes_on_line[(second_line, second_stop)]:
|
| 585 |
+
for start, end in ((source, target), (target, source)):
|
| 586 |
+
adjacency[start].append(
|
| 587 |
+
Edge(
|
| 588 |
+
target=end,
|
| 589 |
+
kind="transfer",
|
| 590 |
+
minutes=cost,
|
| 591 |
+
walk_minutes=walk_minutes,
|
| 592 |
+
walk_distance_m=distance,
|
| 593 |
+
transfer_penalty=TRANSFER_PENALTY_MIN,
|
| 594 |
+
)
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
# If the same (source, target) node pair was reached twice, keep
|
| 598 |
+
# the cheapest way to make that change.
|
| 599 |
+
for source, edges in adjacency.items():
|
| 600 |
+
cheapest: dict[Node, Edge] = {}
|
| 601 |
+
for edge in edges:
|
| 602 |
+
current = cheapest.get(edge.target)
|
| 603 |
+
if current is None or (edge.minutes, edge.walk_minutes) < (
|
| 604 |
+
current.minutes,
|
| 605 |
+
current.walk_minutes,
|
| 606 |
+
):
|
| 607 |
+
cheapest[edge.target] = edge
|
| 608 |
+
adjacency[source] = list(cheapest.values())
|
| 609 |
+
|
| 610 |
+
return adjacency
|
| 611 |
+
|
| 612 |
+
# ------------------------------------------------------------------
|
| 613 |
+
# Loading the real data.
|
| 614 |
+
# ------------------------------------------------------------------
|
| 615 |
+
@classmethod
|
| 616 |
+
def from_data(cls, data, corrections_path=None) -> "Network":
|
| 617 |
+
termini: dict[LineKey, tuple[str | None, str | None]] = {}
|
| 618 |
+
for row in data.lignes.itertuples(index=False):
|
| 619 |
+
key = (str(row.compagnie), str(row.ligne))
|
| 620 |
+
if key not in termini:
|
| 621 |
+
termini[key] = (str(row.terminus_a), str(row.terminus_b))
|
| 622 |
+
|
| 623 |
+
lines: list[Line] = []
|
| 624 |
+
line_orders: dict[LineKey, list[int]] = {}
|
| 625 |
+
grouped = data.itineraires.groupby(["compagnie", "ligne"], sort=False)
|
| 626 |
+
for (company, name), group in grouped:
|
| 627 |
+
ordered = group.sort_values("ordre")
|
| 628 |
+
stops = tuple(str(stop) for stop in ordered["arret"])
|
| 629 |
+
if len(stops) < 2:
|
| 630 |
+
continue
|
| 631 |
+
line_orders[(str(company), str(name))] = [
|
| 632 |
+
int(ordre) for ordre in ordered["ordre"]
|
| 633 |
+
]
|
| 634 |
+
terminus_a, terminus_b = termini.get(
|
| 635 |
+
(str(company), str(name)), (None, None)
|
| 636 |
+
)
|
| 637 |
+
lines.append(
|
| 638 |
+
Line(
|
| 639 |
+
company=str(company),
|
| 640 |
+
name=str(name),
|
| 641 |
+
stops=stops,
|
| 642 |
+
terminus_a=terminus_a,
|
| 643 |
+
terminus_b=terminus_b,
|
| 644 |
+
)
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
# Field corrections are layered on top of the downloaded itinerary
|
| 648 |
+
# before coordinates and graph nodes are built.
|
| 649 |
+
from .corrections import apply_corrections, load_corrections
|
| 650 |
+
|
| 651 |
+
known_stops = {
|
| 652 |
+
str(row.arret) for row in data.arrets.itertuples(index=False)
|
| 653 |
+
}
|
| 654 |
+
known_stops.update(
|
| 655 |
+
stop for line in lines for stop in line.stops
|
| 656 |
+
)
|
| 657 |
+
corrected = apply_corrections(
|
| 658 |
+
lines,
|
| 659 |
+
load_corrections(corrections_path),
|
| 660 |
+
known_stops,
|
| 661 |
+
)
|
| 662 |
+
lines = corrected.lines
|
| 663 |
+
|
| 664 |
+
stop_coords: dict[str, tuple[float, float]] = {}
|
| 665 |
+
stop_confidence: dict[str, str] = {}
|
| 666 |
+
for row in data.arrets.itertuples(index=False):
|
| 667 |
+
stop = str(row.arret)
|
| 668 |
+
if stop not in stop_coords:
|
| 669 |
+
lat = _number(row.lat)
|
| 670 |
+
lon = _number(row.lon)
|
| 671 |
+
if lat is not None and lon is not None:
|
| 672 |
+
stop_coords[stop] = (lat, lon)
|
| 673 |
+
confidence = getattr(row, "confiance", None)
|
| 674 |
+
if isinstance(confidence, str) and stop not in stop_confidence:
|
| 675 |
+
stop_confidence[stop] = confidence
|
| 676 |
+
|
| 677 |
+
# Some stops in itineraires have no coordinate row of their own.
|
| 678 |
+
# If a place with the same normalized name exists in lieux_geo,
|
| 679 |
+
# borrow its position. This is still only a best effort.
|
| 680 |
+
place_coords: dict[str, tuple[float, float]] = {}
|
| 681 |
+
for row in data.lieux.itertuples(index=False):
|
| 682 |
+
lat = _number(row.lat)
|
| 683 |
+
lon = _number(row.lon)
|
| 684 |
+
if lat is None or lon is None:
|
| 685 |
+
continue
|
| 686 |
+
normalized = normalize_name(row.lieu)
|
| 687 |
+
place_coords.setdefault(normalized, (lat, lon))
|
| 688 |
+
|
| 689 |
+
for stop in {stop for line in lines for stop in line.stops}:
|
| 690 |
+
if stop in stop_coords:
|
| 691 |
+
continue
|
| 692 |
+
borrowed = place_coords.get(normalize_name(stop))
|
| 693 |
+
if borrowed is not None:
|
| 694 |
+
stop_coords[stop] = borrowed
|
| 695 |
+
stop_confidence.setdefault(stop, "estimee")
|
| 696 |
+
|
| 697 |
+
# Une position fiable sur une ligne situe aussi un arrêt qui n'en avait pas
|
| 698 |
+
# de bonne (« Sandaga », « Point E », nouveaux noms officiels de Dem Dikk).
|
| 699 |
+
by_order = getattr(data, "positions_ligne", {})
|
| 700 |
+
sure_by_order = getattr(data, "positions_sures", {})
|
| 701 |
+
raw_positions: dict[LineKey, list] = {}
|
| 702 |
+
raw_sure: dict[LineKey, list] = {}
|
| 703 |
+
proposals: dict[str, list[tuple[tuple[float, float], bool]]] = defaultdict(list)
|
| 704 |
+
for line in lines:
|
| 705 |
+
orders = line_orders.get(line.key)
|
| 706 |
+
per_line = by_order.get(line.key)
|
| 707 |
+
if not per_line or orders is None or len(orders) != len(line.stops):
|
| 708 |
+
continue
|
| 709 |
+
raw_positions[line.key] = [per_line.get(ordre, ...) for ordre in orders]
|
| 710 |
+
raw_sure[line.key] = [
|
| 711 |
+
sure_by_order.get(line.key, {}).get(ordre, ...) for ordre in orders
|
| 712 |
+
]
|
| 713 |
+
for stop, ordre in zip(line.stops, orders):
|
| 714 |
+
position = per_line.get(ordre)
|
| 715 |
+
if position is not None:
|
| 716 |
+
proposals[stop].append(
|
| 717 |
+
(position, sure_by_order.get(line.key, {}).get(ordre, False))
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
# Une ligne seule ne déplace pas un arrêt pour tout le réseau : sa position
|
| 721 |
+
# peut être fausse (Tata 35 met Pikine Texaco près de Ngor, ce qui créait une
|
| 722 |
+
# correspondance à pied entre les deux). Il faut deux lignes d'accord, ou
|
| 723 |
+
# que l'arrêt n'ait encore aucune position. Si toutes les lignes qui le
|
| 724 |
+
# desservent s'accordent, elles priment même sur une position « bonne » :
|
| 725 |
+
# AIBD, seulement sur TAF TAF, restait à Grand Yoff dans arrets_geo.csv.
|
| 726 |
+
served = Counter(stop for line in lines for stop in line.stops)
|
| 727 |
+
for stop, proposed in proposals.items():
|
| 728 |
+
position, sure, supporters = max(
|
| 729 |
+
(
|
| 730 |
+
(
|
| 731 |
+
candidate,
|
| 732 |
+
is_sure,
|
| 733 |
+
sum(
|
| 734 |
+
haversine_m(candidate, other) <= POSITION_AGREEMENT_M
|
| 735 |
+
for other, _ in proposed
|
| 736 |
+
),
|
| 737 |
+
)
|
| 738 |
+
for candidate, is_sure in proposed
|
| 739 |
+
),
|
| 740 |
+
key=lambda item: (item[2], item[1]),
|
| 741 |
+
)
|
| 742 |
+
if stop not in stop_coords:
|
| 743 |
+
stop_coords[stop] = position
|
| 744 |
+
stop_confidence[stop] = (
|
| 745 |
+
"bonne" if sure and supporters >= 2 else "estimee"
|
| 746 |
+
)
|
| 747 |
+
elif (
|
| 748 |
+
supporters == len(proposed) == served[stop]
|
| 749 |
+
and haversine_m(position, stop_coords[stop]) > POSITION_AGREEMENT_M
|
| 750 |
+
):
|
| 751 |
+
stop_coords[stop] = position
|
| 752 |
+
stop_confidence[stop] = "bonne" if sure else "estimee"
|
| 753 |
+
elif (
|
| 754 |
+
sure
|
| 755 |
+
and supporters >= 2
|
| 756 |
+
and stop_confidence.get(stop) != "bonne"
|
| 757 |
+
):
|
| 758 |
+
stop_coords[stop] = position
|
| 759 |
+
stop_confidence[stop] = "bonne"
|
| 760 |
+
|
| 761 |
+
# Les arrêts restants sont placés à vol d'oiseau le long de leur
|
| 762 |
+
# ligne, uniquement en mémoire : les CSV ne sont jamais modifiés.
|
| 763 |
+
stop_coords, stop_confidence = interpolate_missing_coordinates(
|
| 764 |
+
lines, stop_coords, stop_confidence
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# Sur chaque ligne : sa propre position si elle en a une, None si elle est
|
| 768 |
+
# connue pour être inconnue, sinon la position générale de l'arrêt.
|
| 769 |
+
line_positions = {
|
| 770 |
+
key: tuple(
|
| 771 |
+
stop_coords.get(stop) if position is ... else position
|
| 772 |
+
for stop, position in zip(by_key[key].stops, positions)
|
| 773 |
+
)
|
| 774 |
+
for by_key in [{line.key: line for line in lines}]
|
| 775 |
+
for key, positions in raw_positions.items()
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
# Sûreté de chaque position sur sa ligne : celle du fichier de la ligne,
|
| 779 |
+
# sinon celle de la position générale (« bonne » seulement).
|
| 780 |
+
line_sure = {
|
| 781 |
+
key: tuple(
|
| 782 |
+
stop_confidence.get(stop) == "bonne" if sure is ... else bool(sure)
|
| 783 |
+
for stop, sure in zip(by_key[key].stops, flags)
|
| 784 |
+
)
|
| 785 |
+
for by_key in [{line.key: line for line in lines}]
|
| 786 |
+
for key, flags in raw_sure.items()
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
# La vraie longueur de route pour les lignes Tata qui ont une trace.
|
| 790 |
+
line_distances: dict[LineKey, tuple] = {}
|
| 791 |
+
traces = getattr(data, "traces", {})
|
| 792 |
+
for line in lines:
|
| 793 |
+
trace = traces.get(line.name) if line.company == "Tata AFTU" else None
|
| 794 |
+
if not trace:
|
| 795 |
+
continue
|
| 796 |
+
positions = line_positions.get(line.key) or tuple(
|
| 797 |
+
stop_coords.get(stop) for stop in line.stops
|
| 798 |
+
)
|
| 799 |
+
measured = distances_sur_trace(trace, positions)
|
| 800 |
+
if measured is not None:
|
| 801 |
+
line_distances[line.key] = measured
|
| 802 |
+
|
| 803 |
+
return cls(
|
| 804 |
+
lines,
|
| 805 |
+
stop_coords,
|
| 806 |
+
stop_confidence,
|
| 807 |
+
line_positions,
|
| 808 |
+
line_distances,
|
| 809 |
+
_legacy_stops(data, lines, stop_coords, stop_confidence),
|
| 810 |
+
line_sure,
|
| 811 |
+
)
|
src/routing/router.py
CHANGED
|
@@ -1,1263 +1,1271 @@
|
|
| 1 |
-
"""Route search with direct trips first, then one or two transfers.
|
| 2 |
-
|
| 3 |
-
The search is Dijkstra over ``(line, direction, stop position)`` nodes.
|
| 4 |
-
The state also remembers how many transfers have been used and which
|
| 5 |
-
lines have been used, so we can return distinct line combinations and
|
| 6 |
-
never loop back onto a line we already rode.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from __future__ import annotations
|
| 10 |
-
|
| 11 |
-
import heapq
|
| 12 |
-
import itertools
|
| 13 |
-
from collections import defaultdict
|
| 14 |
-
from dataclasses import dataclass
|
| 15 |
-
from typing import Callable
|
| 16 |
-
|
| 17 |
-
from .network import (
|
| 18 |
-
BUS_SPEED_M_PER_MIN,
|
| 19 |
-
WALK_SPEED_M_PER_MIN,
|
| 20 |
-
Edge,
|
| 21 |
-
LineKey,
|
| 22 |
-
Network,
|
| 23 |
-
Node,
|
| 24 |
-
haversine_m,
|
| 25 |
-
)
|
| 26 |
-
from .places import (
|
| 27 |
-
PlaceCandidate,
|
| 28 |
-
PlaceIndex,
|
| 29 |
-
normalize_name,
|
| 30 |
-
prefer_exact_matches,
|
| 31 |
-
representative_coordinates,
|
| 32 |
-
)
|
| 33 |
-
|
| 34 |
-
MAX_TRANSFERS = 2
|
| 35 |
-
ACCESS_WALK_RADIUS_M = 1200.0
|
| 36 |
-
NEARBY_EXACT_STOP_RADIUS_M = 900.0
|
| 37 |
-
# Autour d'un lieu nommé par l'usager, un arrêt conseillé doit rester à 600 m :
|
| 38 |
-
# au-delà, la carte ne donne plus de nom d'arrêt (« MTOA » ouvrait « Central
|
| 39 |
-
# Bel Air (MTOA) », 15 km au sud) et dit de chercher l'arrêt le plus proche.
|
| 40 |
-
# Le calcul du trajet, lui, n'est pas restreint : une pénalité ici faisait
|
| 41 |
-
# disparaître les Dem Dikk 10 et 13 de Liberté 5 (terminus de Dieuppeul).
|
| 42 |
-
PLACE_STOP_RADIUS_M = 600.0
|
| 43 |
-
MAX_NEARBY_STOPS = 14
|
| 44 |
-
# Écart toléré entre la position générale d'un arrêt (celle qui a servi à
|
| 45 |
-
# compter la marche) et sa position sur une ligne donnée. Au-delà, ce n'est
|
| 46 |
-
# pas le même arrêt mais un homonyme : « Sipres » est situé à Amitié, près de
|
| 47 |
-
# l'UCAD, alors que le « SIPRES » de Dem Dikk 220 est à Rufisque. Sans ce
|
| 48 |
-
# garde-fou, Malika -> UCAD proposait la 220 avec descente « à 10 min à pied ».
|
| 49 |
-
MAX_ECART_HOMONYME_M = 1_500.0
|
| 50 |
-
MAX_LABELS_PER_STATE = 6
|
| 51 |
-
MAX_EXPANSIONS = 250_000
|
| 52 |
-
DETOUR_LIMIT = 1.8
|
| 53 |
-
DOWNTOWN_RADIUS_M = 1_500.0
|
| 54 |
-
MIN_LEG_MINUTES = 2.0
|
| 55 |
-
TRANSFER_SCORE_MINUTES = 15.0
|
| 56 |
-
DIRECT_ALLOWANCE_MINUTES = 15.0
|
| 57 |
-
MIN_TRANSFER_ADVANTAGE_MINUTES = 10.0
|
| 58 |
-
MAX_WALKABLE_BUS_LEG_M = 600.0
|
| 59 |
-
# La marche à pied suit rarement la ligne droite : 1,3 fois la distance
|
| 60 |
-
# vol d'oiseau, à 80 m/min (environ 4,8 km/h).
|
| 61 |
-
WALK_DETOUR_FACTOR = 1.3
|
| 62 |
-
MAX_WALK_ONLY_MINUTES = 40.0
|
| 63 |
-
# A trip three times slower than the best option is not a useful
|
| 64 |
-
# alternative. This also catches routes with missing coordinates that
|
| 65 |
-
# escape the distance-based detour check.
|
| 66 |
-
MAX_TIME_VS_BEST = 3.0
|
| 67 |
-
# Un rapport ne veut rien dire sur un trajet très court : à côté d'une ligne à 2 min,
|
| 68 |
-
# Tata 62 (10 min, Sahm -> Colobane) passait pour absurdement lent.
|
| 69 |
-
MIN_TIME_MARGIN_MINUTES = 20.0
|
| 70 |
-
# La recherche s'arrête quand plus rien ne peut approcher le meilleur trajet trouvé :
|
| 71 |
-
# au-delà, un trajet serait écarté ou jamais affiché.
|
| 72 |
-
MAX_SCORE_ABOVE_BEST = 30.0
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def walking_minutes(
|
| 76 |
-
a: tuple[float, float],
|
| 77 |
-
b: tuple[float, float],
|
| 78 |
-
) -> float:
|
| 79 |
-
"""Temps de marche estimé entre deux points, en minutes."""
|
| 80 |
-
|
| 81 |
-
return haversine_m(a, b) * WALK_DETOUR_FACTOR / WALK_SPEED_M_PER_MIN
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
# These are the downtown / Plateau names. A trip may pass through them
|
| 85 |
-
# when they are close to the start or the destination, but not as a random
|
| 86 |
-
# shortcut between two outer neighbourhoods.
|
| 87 |
-
DOWNTOWN_STOP_NAMES = {
|
| 88 |
-
normalize_name(name)
|
| 89 |
-
for name in (
|
| 90 |
-
"Palais 1",
|
| 91 |
-
"Palais 2",
|
| 92 |
-
"Palais",
|
| 93 |
-
"Centre-Ville",
|
| 94 |
-
"Plateau",
|
| 95 |
-
"Place Leclerc",
|
| 96 |
-
"Place de l'Indépendance",
|
| 97 |
-
"Médina",
|
| 98 |
-
)
|
| 99 |
-
}
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
class RouteError(Exception):
|
| 103 |
-
"""Base class for route errors."""
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
class PlaceNotFoundError(RouteError):
|
| 107 |
-
def __init__(self, query: str, suggestions: list[tuple[str, float]]) -> None:
|
| 108 |
-
self.query = query
|
| 109 |
-
self.suggestions = suggestions
|
| 110 |
-
super().__init__(f"Unknown place: {query}")
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
class NoRouteFoundError(RouteError):
|
| 114 |
-
pass
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
@dataclass(frozen=True)
|
| 118 |
-
class Walk:
|
| 119 |
-
kind: str # "access", "transfer", or "egress"
|
| 120 |
-
from_place: str
|
| 121 |
-
to_place: str
|
| 122 |
-
minutes: float
|
| 123 |
-
distance_m: float | None = None
|
| 124 |
-
after_leg: int = 0 # 0 = before the first leg
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
def _has_endpoint_walk(trip: Trip) -> bool:
|
| 128 |
-
return any(
|
| 129 |
-
walk.kind in {"access", "egress"} and walk.minutes > 0
|
| 130 |
-
for walk in trip.walks
|
| 131 |
-
)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
@dataclass(frozen=True)
|
| 135 |
-
class Leg:
|
| 136 |
-
operator: str
|
| 137 |
-
line: str
|
| 138 |
-
board_stop: str
|
| 139 |
-
alight_stop: str
|
| 140 |
-
direction: str # terminus shown on the bus
|
| 141 |
-
num_stops: int
|
| 142 |
-
minutes: float
|
| 143 |
-
distance_m: float | None = None
|
| 144 |
-
estimated: bool = False
|
| 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 |
-
direct
|
| 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 |
-
if distance
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
if not
|
| 301 |
-
return
|
| 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 |
-
self
|
| 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 |
-
for stop in
|
| 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 |
-
self,
|
| 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 |
-
self.
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
origin_matches, "access",
|
| 578 |
-
)
|
| 579 |
-
|
| 580 |
-
destination_matches, "egress",
|
| 581 |
-
)
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
#
|
| 697 |
-
#
|
| 698 |
-
#
|
| 699 |
-
if
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
#
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
trips = [
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
)
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
)
|
| 802 |
-
if
|
| 803 |
-
|
| 804 |
-
)
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
stop
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
)
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
if
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
if
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
)
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
if
|
| 933 |
-
continue
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
label
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
|
| 1060 |
-
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
|
| 1073 |
-
|
| 1074 |
-
|
| 1075 |
-
|
| 1076 |
-
|
| 1077 |
-
|
| 1078 |
-
|
| 1079 |
-
|
| 1080 |
-
|
| 1081 |
-
|
| 1082 |
-
|
| 1083 |
-
|
| 1084 |
-
|
| 1085 |
-
|
| 1086 |
-
|
| 1087 |
-
|
| 1088 |
-
|
| 1089 |
-
|
| 1090 |
-
|
| 1091 |
-
|
| 1092 |
-
|
| 1093 |
-
|
| 1094 |
-
|
| 1095 |
-
|
| 1096 |
-
|
| 1097 |
-
|
| 1098 |
-
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
|
| 1114 |
-
|
| 1115 |
-
|
| 1116 |
-
|
| 1117 |
-
|
| 1118 |
-
|
| 1119 |
-
|
| 1120 |
-
|
| 1121 |
-
|
| 1122 |
-
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
|
| 1127 |
-
|
| 1128 |
-
|
| 1129 |
-
|
| 1130 |
-
|
| 1131 |
-
|
| 1132 |
-
|
| 1133 |
-
|
| 1134 |
-
|
| 1135 |
-
|
| 1136 |
-
|
| 1137 |
-
|
| 1138 |
-
|
| 1139 |
-
|
| 1140 |
-
|
| 1141 |
-
|
| 1142 |
-
|
| 1143 |
-
|
| 1144 |
-
|
| 1145 |
-
|
| 1146 |
-
|
| 1147 |
-
|
| 1148 |
-
|
| 1149 |
-
|
| 1150 |
-
|
| 1151 |
-
|
| 1152 |
-
|
| 1153 |
-
|
| 1154 |
-
|
| 1155 |
-
"
|
| 1156 |
-
|
| 1157 |
-
|
| 1158 |
-
|
| 1159 |
-
|
| 1160 |
-
|
| 1161 |
-
|
| 1162 |
-
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
|
| 1166 |
-
|
| 1167 |
-
|
| 1168 |
-
|
| 1169 |
-
|
| 1170 |
-
if
|
| 1171 |
-
|
| 1172 |
-
|
| 1173 |
-
|
| 1174 |
-
|
| 1175 |
-
|
| 1176 |
-
|
| 1177 |
-
|
| 1178 |
-
|
| 1179 |
-
|
| 1180 |
-
|
| 1181 |
-
|
| 1182 |
-
|
| 1183 |
-
|
| 1184 |
-
|
| 1185 |
-
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
|
| 1190 |
-
|
| 1191 |
-
|
| 1192 |
-
|
| 1193 |
-
|
| 1194 |
-
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
|
| 1200 |
-
|
| 1201 |
-
|
| 1202 |
-
|
| 1203 |
-
|
| 1204 |
-
|
| 1205 |
-
|
| 1206 |
-
|
| 1207 |
-
|
| 1208 |
-
|
| 1209 |
-
|
| 1210 |
-
|
| 1211 |
-
|
| 1212 |
-
|
| 1213 |
-
|
| 1214 |
-
|
| 1215 |
-
|
| 1216 |
-
|
| 1217 |
-
|
| 1218 |
-
|
| 1219 |
-
|
| 1220 |
-
|
| 1221 |
-
|
| 1222 |
-
|
| 1223 |
-
|
| 1224 |
-
|
| 1225 |
-
|
| 1226 |
-
|
| 1227 |
-
|
| 1228 |
-
|
| 1229 |
-
|
| 1230 |
-
|
| 1231 |
-
|
| 1232 |
-
|
| 1233 |
-
|
| 1234 |
-
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
-
|
| 1243 |
-
|
| 1244 |
-
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
|
| 1249 |
-
|
| 1250 |
-
|
| 1251 |
-
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
-
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
|
| 1259 |
-
|
| 1260 |
-
|
| 1261 |
-
|
| 1262 |
-
|
| 1263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Route search with direct trips first, then one or two transfers.
|
| 2 |
+
|
| 3 |
+
The search is Dijkstra over ``(line, direction, stop position)`` nodes.
|
| 4 |
+
The state also remembers how many transfers have been used and which
|
| 5 |
+
lines have been used, so we can return distinct line combinations and
|
| 6 |
+
never loop back onto a line we already rode.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import heapq
|
| 12 |
+
import itertools
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Callable
|
| 16 |
+
|
| 17 |
+
from .network import (
|
| 18 |
+
BUS_SPEED_M_PER_MIN,
|
| 19 |
+
WALK_SPEED_M_PER_MIN,
|
| 20 |
+
Edge,
|
| 21 |
+
LineKey,
|
| 22 |
+
Network,
|
| 23 |
+
Node,
|
| 24 |
+
haversine_m,
|
| 25 |
+
)
|
| 26 |
+
from .places import (
|
| 27 |
+
PlaceCandidate,
|
| 28 |
+
PlaceIndex,
|
| 29 |
+
normalize_name,
|
| 30 |
+
prefer_exact_matches,
|
| 31 |
+
representative_coordinates,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
MAX_TRANSFERS = 2
|
| 35 |
+
ACCESS_WALK_RADIUS_M = 1200.0
|
| 36 |
+
NEARBY_EXACT_STOP_RADIUS_M = 900.0
|
| 37 |
+
# Autour d'un lieu nommé par l'usager, un arrêt conseillé doit rester à 600 m :
|
| 38 |
+
# au-delà, la carte ne donne plus de nom d'arrêt (« MTOA » ouvrait « Central
|
| 39 |
+
# Bel Air (MTOA) », 15 km au sud) et dit de chercher l'arrêt le plus proche.
|
| 40 |
+
# Le calcul du trajet, lui, n'est pas restreint : une pénalité ici faisait
|
| 41 |
+
# disparaître les Dem Dikk 10 et 13 de Liberté 5 (terminus de Dieuppeul).
|
| 42 |
+
PLACE_STOP_RADIUS_M = 600.0
|
| 43 |
+
MAX_NEARBY_STOPS = 14
|
| 44 |
+
# Écart toléré entre la position générale d'un arrêt (celle qui a servi à
|
| 45 |
+
# compter la marche) et sa position sur une ligne donnée. Au-delà, ce n'est
|
| 46 |
+
# pas le même arrêt mais un homonyme : « Sipres » est situé à Amitié, près de
|
| 47 |
+
# l'UCAD, alors que le « SIPRES » de Dem Dikk 220 est à Rufisque. Sans ce
|
| 48 |
+
# garde-fou, Malika -> UCAD proposait la 220 avec descente « à 10 min à pied ».
|
| 49 |
+
MAX_ECART_HOMONYME_M = 1_500.0
|
| 50 |
+
MAX_LABELS_PER_STATE = 6
|
| 51 |
+
MAX_EXPANSIONS = 250_000
|
| 52 |
+
DETOUR_LIMIT = 1.8
|
| 53 |
+
DOWNTOWN_RADIUS_M = 1_500.0
|
| 54 |
+
MIN_LEG_MINUTES = 2.0
|
| 55 |
+
TRANSFER_SCORE_MINUTES = 15.0
|
| 56 |
+
DIRECT_ALLOWANCE_MINUTES = 15.0
|
| 57 |
+
MIN_TRANSFER_ADVANTAGE_MINUTES = 10.0
|
| 58 |
+
MAX_WALKABLE_BUS_LEG_M = 600.0
|
| 59 |
+
# La marche à pied suit rarement la ligne droite : 1,3 fois la distance
|
| 60 |
+
# vol d'oiseau, à 80 m/min (environ 4,8 km/h).
|
| 61 |
+
WALK_DETOUR_FACTOR = 1.3
|
| 62 |
+
MAX_WALK_ONLY_MINUTES = 40.0
|
| 63 |
+
# A trip three times slower than the best option is not a useful
|
| 64 |
+
# alternative. This also catches routes with missing coordinates that
|
| 65 |
+
# escape the distance-based detour check.
|
| 66 |
+
MAX_TIME_VS_BEST = 3.0
|
| 67 |
+
# Un rapport ne veut rien dire sur un trajet très court : à côté d'une ligne à 2 min,
|
| 68 |
+
# Tata 62 (10 min, Sahm -> Colobane) passait pour absurdement lent.
|
| 69 |
+
MIN_TIME_MARGIN_MINUTES = 20.0
|
| 70 |
+
# La recherche s'arrête quand plus rien ne peut approcher le meilleur trajet trouvé :
|
| 71 |
+
# au-delà, un trajet serait écarté ou jamais affiché.
|
| 72 |
+
MAX_SCORE_ABOVE_BEST = 30.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def walking_minutes(
|
| 76 |
+
a: tuple[float, float],
|
| 77 |
+
b: tuple[float, float],
|
| 78 |
+
) -> float:
|
| 79 |
+
"""Temps de marche estimé entre deux points, en minutes."""
|
| 80 |
+
|
| 81 |
+
return haversine_m(a, b) * WALK_DETOUR_FACTOR / WALK_SPEED_M_PER_MIN
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# These are the downtown / Plateau names. A trip may pass through them
|
| 85 |
+
# when they are close to the start or the destination, but not as a random
|
| 86 |
+
# shortcut between two outer neighbourhoods.
|
| 87 |
+
DOWNTOWN_STOP_NAMES = {
|
| 88 |
+
normalize_name(name)
|
| 89 |
+
for name in (
|
| 90 |
+
"Palais 1",
|
| 91 |
+
"Palais 2",
|
| 92 |
+
"Palais",
|
| 93 |
+
"Centre-Ville",
|
| 94 |
+
"Plateau",
|
| 95 |
+
"Place Leclerc",
|
| 96 |
+
"Place de l'Indépendance",
|
| 97 |
+
"Médina",
|
| 98 |
+
)
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class RouteError(Exception):
|
| 103 |
+
"""Base class for route errors."""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class PlaceNotFoundError(RouteError):
|
| 107 |
+
def __init__(self, query: str, suggestions: list[tuple[str, float]]) -> None:
|
| 108 |
+
self.query = query
|
| 109 |
+
self.suggestions = suggestions
|
| 110 |
+
super().__init__(f"Unknown place: {query}")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class NoRouteFoundError(RouteError):
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@dataclass(frozen=True)
|
| 118 |
+
class Walk:
|
| 119 |
+
kind: str # "access", "transfer", or "egress"
|
| 120 |
+
from_place: str
|
| 121 |
+
to_place: str
|
| 122 |
+
minutes: float
|
| 123 |
+
distance_m: float | None = None
|
| 124 |
+
after_leg: int = 0 # 0 = before the first leg
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _has_endpoint_walk(trip: Trip) -> bool:
|
| 128 |
+
return any(
|
| 129 |
+
walk.kind in {"access", "egress"} and walk.minutes > 0
|
| 130 |
+
for walk in trip.walks
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@dataclass(frozen=True)
|
| 135 |
+
class Leg:
|
| 136 |
+
operator: str
|
| 137 |
+
line: str
|
| 138 |
+
board_stop: str
|
| 139 |
+
alight_stop: str
|
| 140 |
+
direction: str # terminus shown on the bus
|
| 141 |
+
num_stops: int
|
| 142 |
+
minutes: float
|
| 143 |
+
distance_m: float | None = None
|
| 144 |
+
estimated: bool = False
|
| 145 |
+
# Position exacte de la montée et de la descente dans ``line.stops`` (sens
|
| 146 |
+
# de la liste). Sur une ligne en boucle, le terminus y figure deux fois :
|
| 147 |
+
# sans ces positions, retrouver l'arrêt par son nom prenait le premier
|
| 148 |
+
# passage et mesurait l'autre sens du tour (Dem Dikk 18, 20).
|
| 149 |
+
board_index: int | None = None
|
| 150 |
+
alight_index: int | None = None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@dataclass(frozen=True)
|
| 154 |
+
class Trip:
|
| 155 |
+
legs: tuple[Leg, ...]
|
| 156 |
+
walks: tuple[Walk, ...]
|
| 157 |
+
total_minutes: float
|
| 158 |
+
transfers: int
|
| 159 |
+
line_combo: tuple[LineKey, ...]
|
| 160 |
+
origin_name: str
|
| 161 |
+
destination_name: str
|
| 162 |
+
total_distance_m: float | None
|
| 163 |
+
straight_line_m: float | None
|
| 164 |
+
detour: bool
|
| 165 |
+
via_downtown: bool
|
| 166 |
+
ridden_stops: tuple[str, ...]
|
| 167 |
+
estimated: bool = False
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def walked_minutes(self) -> float:
|
| 171 |
+
return sum(walk.minutes for walk in self.walks)
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def score(self) -> float:
|
| 175 |
+
return self.total_minutes + TRANSFER_SCORE_MINUTES * self.transfers
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@dataclass(frozen=True)
|
| 179 |
+
class ResolvedPlace:
|
| 180 |
+
"""Un lieu déjà résolu en arrêts du réseau (par GuindiMa, pas par v2)."""
|
| 181 |
+
|
| 182 |
+
stops: tuple[str, ...]
|
| 183 |
+
coords: tuple[float, float] | None = None
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@dataclass(frozen=True)
|
| 187 |
+
class AccessPoint:
|
| 188 |
+
stop: str
|
| 189 |
+
walk: Walk
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _rank_key(trip: Trip) -> tuple[float, float, float, int]:
|
| 193 |
+
distance = (
|
| 194 |
+
trip.total_distance_m
|
| 195 |
+
if trip.total_distance_m is not None
|
| 196 |
+
else float("inf")
|
| 197 |
+
)
|
| 198 |
+
return trip.score, trip.total_minutes, distance, trip.transfers
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# Au-delà de cette marche jusqu'à l'arrêt de montée, un bus direct n'est plus
|
| 202 |
+
# classé sur sa seule durée : il passe après ceux qui partent tout près.
|
| 203 |
+
MAX_ACCESS_WALK_FOR_FASTEST_MINUTES = 10.0
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def direct_rank_key(trip: Trip) -> tuple[bool, float]:
|
| 207 |
+
"""Entre bus directs : le plus rapide d'abord (marche + bus), si l'on monte près."""
|
| 208 |
+
|
| 209 |
+
access = sum(walk.minutes for walk in trip.walks if walk.kind == "access")
|
| 210 |
+
return access >= MAX_ACCESS_WALK_FOR_FASTEST_MINUTES, trip.total_minutes
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def rank_trips(trips: list[Trip], max_trips: int | None = None) -> list[Trip]:
|
| 214 |
+
"""Order trips by score, promoting a direct trip within 15 minutes.
|
| 215 |
+
|
| 216 |
+
Score is ``total_minutes + 15 * transfers``. A direct trip is shown
|
| 217 |
+
first when it is at most 15 minutes slower than the best score, because
|
| 218 |
+
avoiding a transfer is worth a short wait.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
# Sur une même ligne, l'arrêt demandé passe avant un voisin à pied : Tata 62
|
| 222 |
+
# dessert Sahm, on ne fait pas marcher l'usager jusqu'à Fass pour gagner une
|
| 223 |
+
# minute sur le papier.
|
| 224 |
+
def preference(trip: Trip) -> tuple:
|
| 225 |
+
return (_has_endpoint_walk(trip), *_rank_key(trip))
|
| 226 |
+
|
| 227 |
+
unique: dict[tuple[LineKey, ...], Trip] = {}
|
| 228 |
+
for trip in trips:
|
| 229 |
+
current = unique.get(trip.line_combo)
|
| 230 |
+
if current is None or preference(trip) < preference(current):
|
| 231 |
+
unique[trip.line_combo] = trip
|
| 232 |
+
|
| 233 |
+
ordered = sorted(unique.values(), key=_rank_key)
|
| 234 |
+
if not ordered:
|
| 235 |
+
return []
|
| 236 |
+
|
| 237 |
+
best_score = ordered[0].score
|
| 238 |
+
direct = [
|
| 239 |
+
trip
|
| 240 |
+
for trip in ordered
|
| 241 |
+
if trip.transfers == 0
|
| 242 |
+
and trip.score <= best_score + DIRECT_ALLOWANCE_MINUTES
|
| 243 |
+
]
|
| 244 |
+
direct.sort(key=direct_rank_key)
|
| 245 |
+
direct_keys = {trip.line_combo for trip in direct}
|
| 246 |
+
rest = [trip for trip in ordered if trip.line_combo not in direct_keys]
|
| 247 |
+
ranked = direct + rest
|
| 248 |
+
return ranked if max_trips is None else ranked[:max_trips]
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _slowest_sensible(fastest: float) -> float:
|
| 252 |
+
return max(fastest * MAX_TIME_VS_BEST, fastest + MIN_TIME_MARGIN_MINUTES)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def keep_sensible_trips(trips: list[Trip]) -> list[Trip]:
|
| 256 |
+
"""Écarte les détours par le centre et les trajets absurdement lents."""
|
| 257 |
+
|
| 258 |
+
# Extra guard for this network: do not cross downtown just to
|
| 259 |
+
# connect two outer neighbourhoods.
|
| 260 |
+
non_downtown = [trip for trip in trips if not trip.via_downtown]
|
| 261 |
+
if non_downtown:
|
| 262 |
+
trips = non_downtown
|
| 263 |
+
|
| 264 |
+
# Do not offer an absurdly slow "alternative" just because it has
|
| 265 |
+
# fewer transfers. If every remaining trip is slow, keep them.
|
| 266 |
+
if trips:
|
| 267 |
+
limit = _slowest_sensible(min(trip.total_minutes for trip in trips))
|
| 268 |
+
sane = [trip for trip in trips if trip.total_minutes <= limit]
|
| 269 |
+
if sane:
|
| 270 |
+
trips = sane
|
| 271 |
+
return trips
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _has_walkable_one_stop_leg(trip: Trip, network: Network) -> bool:
|
| 275 |
+
"""A one-stop bus ride under 600 m is not worth waiting for a bus."""
|
| 276 |
+
|
| 277 |
+
for leg in trip.legs:
|
| 278 |
+
if leg.num_stops != 1:
|
| 279 |
+
continue
|
| 280 |
+
distance = leg.distance_m
|
| 281 |
+
if distance is None:
|
| 282 |
+
board = network.coords(leg.board_stop)
|
| 283 |
+
alight = network.coords(leg.alight_stop)
|
| 284 |
+
if board is None or alight is None:
|
| 285 |
+
continue
|
| 286 |
+
distance = haversine_m(board, alight)
|
| 287 |
+
if distance <= MAX_WALKABLE_BUS_LEG_M:
|
| 288 |
+
return True
|
| 289 |
+
return False
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def remove_dominated_trips(trips: list[Trip], network: Network) -> list[Trip]:
|
| 293 |
+
"""Hide slow transfer-heavy trips and pointless one-stop bus rides.
|
| 294 |
+
|
| 295 |
+
A trip with more transfers must save at least ten minutes over the best
|
| 296 |
+
trip with fewer transfers. One-stop bus legs under 600 m are hidden too.
|
| 297 |
+
If every trip is filtered, keep the best one so the answer is never empty.
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
if not trips:
|
| 301 |
+
return []
|
| 302 |
+
|
| 303 |
+
candidates = [
|
| 304 |
+
trip for trip in trips if not _has_walkable_one_stop_leg(trip, network)
|
| 305 |
+
]
|
| 306 |
+
if not candidates:
|
| 307 |
+
return trips[:1]
|
| 308 |
+
|
| 309 |
+
kept: list[Trip] = []
|
| 310 |
+
for trip in candidates:
|
| 311 |
+
faster_fewer = [
|
| 312 |
+
other.total_minutes
|
| 313 |
+
for other in candidates
|
| 314 |
+
if other.transfers < trip.transfers
|
| 315 |
+
]
|
| 316 |
+
if faster_fewer:
|
| 317 |
+
best_fewer = min(faster_fewer)
|
| 318 |
+
advantage = best_fewer - trip.total_minutes
|
| 319 |
+
if advantage < MIN_TRANSFER_ADVANTAGE_MINUTES - 1e-9:
|
| 320 |
+
continue
|
| 321 |
+
kept.append(trip)
|
| 322 |
+
return kept or candidates[:1]
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@dataclass(frozen=True)
|
| 326 |
+
class _Step:
|
| 327 |
+
kind: str # "access", "ride", "transfer", "egress"
|
| 328 |
+
from_stop: str
|
| 329 |
+
to_stop: str
|
| 330 |
+
minutes: float
|
| 331 |
+
line: LineKey
|
| 332 |
+
direction: int
|
| 333 |
+
from_index: int | None
|
| 334 |
+
to_index: int | None
|
| 335 |
+
distance_m: float | None = None
|
| 336 |
+
walk_minutes: float = 0.0
|
| 337 |
+
walk_distance_m: float | None = None
|
| 338 |
+
transfer_penalty: float = 0.0
|
| 339 |
+
estimated: bool = False
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@dataclass(frozen=True)
|
| 343 |
+
class _Label:
|
| 344 |
+
node: Node
|
| 345 |
+
transfers: int
|
| 346 |
+
cost: float
|
| 347 |
+
combo: tuple[LineKey, ...]
|
| 348 |
+
steps: tuple[_Step, ...]
|
| 349 |
+
rode_since_transfer: bool
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class RouteEngine:
|
| 353 |
+
def __init__(self, network: Network, place_index: PlaceIndex | None = None) -> None:
|
| 354 |
+
self.network = network
|
| 355 |
+
self.place_index = place_index or PlaceIndex.from_network(network)
|
| 356 |
+
|
| 357 |
+
# ------------------------------------------------------------------
|
| 358 |
+
# Endpoint preparation.
|
| 359 |
+
# ------------------------------------------------------------------
|
| 360 |
+
def _access_points(
|
| 361 |
+
self,
|
| 362 |
+
candidate: PlaceCandidate,
|
| 363 |
+
kind: str,
|
| 364 |
+
include_nearby: bool = True,
|
| 365 |
+
nearby_stop_ok: Callable[[str], bool] | None = None,
|
| 366 |
+
) -> list[AccessPoint]:
|
| 367 |
+
"""Stops the user can reach from this place, with the walk."""
|
| 368 |
+
|
| 369 |
+
points: dict[str, AccessPoint] = {}
|
| 370 |
+
|
| 371 |
+
# Exact normalized stop names win: "Malika" and "Sahm" board at the
|
| 372 |
+
# stop itself, without an invented walk.
|
| 373 |
+
exact_stops = self.network.stops_for_normalized(candidate.normalized)
|
| 374 |
+
for stop in exact_stops:
|
| 375 |
+
points[stop] = AccessPoint(
|
| 376 |
+
stop=stop,
|
| 377 |
+
walk=Walk(
|
| 378 |
+
kind=kind,
|
| 379 |
+
from_place=candidate.name,
|
| 380 |
+
to_place=stop,
|
| 381 |
+
minutes=0.0,
|
| 382 |
+
distance_m=0.0,
|
| 383 |
+
after_leg=0,
|
| 384 |
+
),
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
# Exact stops also open every stop within a short walk. This lets a
|
| 388 |
+
# neighbourhood such as Médina use a nearby avenue without losing the
|
| 389 |
+
# exact stop itself. The exact stop keeps its zero-minute walk.
|
| 390 |
+
# Un arrêt à la position incertaine n'ouvre rien et n'est proposé à
|
| 391 |
+
# personne : « Malika Terminus », mal placé, amenait Almadies -> Malika à
|
| 392 |
+
# Gadaye « à 4 min à pied », à 4 km de là.
|
| 393 |
+
exact_coords = [
|
| 394 |
+
coords
|
| 395 |
+
for stop in exact_stops
|
| 396 |
+
if (coords := self.network.coords(stop)) is not None
|
| 397 |
+
and (nearby_stop_ok is None or nearby_stop_ok(stop))
|
| 398 |
+
]
|
| 399 |
+
if exact_coords and include_nearby:
|
| 400 |
+
nearby: list[tuple[float, str]] = []
|
| 401 |
+
for stop in self.network.stop_names:
|
| 402 |
+
if stop in points:
|
| 403 |
+
continue
|
| 404 |
+
if nearby_stop_ok is not None and not nearby_stop_ok(stop):
|
| 405 |
+
continue
|
| 406 |
+
stop_coords = self.network.coords(stop)
|
| 407 |
+
if stop_coords is None:
|
| 408 |
+
continue
|
| 409 |
+
distance = min(
|
| 410 |
+
haversine_m(coords, stop_coords) for coords in exact_coords
|
| 411 |
+
)
|
| 412 |
+
if distance > NEARBY_EXACT_STOP_RADIUS_M:
|
| 413 |
+
continue
|
| 414 |
+
if (
|
| 415 |
+
distance <= 1.0
|
| 416 |
+
and normalize_name(stop) != candidate.normalized
|
| 417 |
+
):
|
| 418 |
+
continue
|
| 419 |
+
nearby.append((distance, stop))
|
| 420 |
+
nearby.sort()
|
| 421 |
+
for distance, stop in nearby:
|
| 422 |
+
points[stop] = AccessPoint(
|
| 423 |
+
stop=stop,
|
| 424 |
+
walk=Walk(
|
| 425 |
+
kind=kind,
|
| 426 |
+
from_place=candidate.name,
|
| 427 |
+
to_place=stop,
|
| 428 |
+
minutes=distance / WALK_SPEED_M_PER_MIN,
|
| 429 |
+
distance_m=distance,
|
| 430 |
+
after_leg=0,
|
| 431 |
+
),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
# A place that is not itself a stop (for example "Palais", which is
|
| 435 |
+
# near Palais 1 and Palais 2) can use the nearest stops.
|
| 436 |
+
if not points and candidate.has_coordinates:
|
| 437 |
+
origin = (float(candidate.lat), float(candidate.lon))
|
| 438 |
+
nearby: list[tuple[float, str]] = []
|
| 439 |
+
for stop in self.network.stop_names:
|
| 440 |
+
stop_coords = self.network.coords(stop)
|
| 441 |
+
if stop_coords is None:
|
| 442 |
+
continue
|
| 443 |
+
distance = haversine_m(origin, stop_coords)
|
| 444 |
+
if distance <= ACCESS_WALK_RADIUS_M:
|
| 445 |
+
nearby.append((distance, stop))
|
| 446 |
+
nearby.sort()
|
| 447 |
+
for distance, stop in nearby[:MAX_NEARBY_STOPS]:
|
| 448 |
+
points[stop] = AccessPoint(
|
| 449 |
+
stop=stop,
|
| 450 |
+
walk=Walk(
|
| 451 |
+
kind=kind,
|
| 452 |
+
from_place=candidate.name,
|
| 453 |
+
to_place=stop,
|
| 454 |
+
minutes=distance / WALK_SPEED_M_PER_MIN,
|
| 455 |
+
distance_m=distance,
|
| 456 |
+
after_leg=0,
|
| 457 |
+
),
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
return list(points.values())
|
| 461 |
+
|
| 462 |
+
def _candidates_for(self, place: ResolvedPlace) -> list[PlaceCandidate]:
|
| 463 |
+
"""Les arrêts résolus, sous la forme que le reste du moteur connaît.
|
| 464 |
+
|
| 465 |
+
Chacun est un arrêt exact : montée sans marche, et les arrêts proches
|
| 466 |
+
restent ouverts par l'élargissement habituel de ``_access_points``.
|
| 467 |
+
"""
|
| 468 |
+
|
| 469 |
+
candidats = []
|
| 470 |
+
for stop in place.stops:
|
| 471 |
+
coords = self.network.coords(stop)
|
| 472 |
+
candidats.append(
|
| 473 |
+
PlaceCandidate(
|
| 474 |
+
name=stop,
|
| 475 |
+
normalized=normalize_name(stop),
|
| 476 |
+
score=100.0,
|
| 477 |
+
lat=coords[0] if coords else None,
|
| 478 |
+
lon=coords[1] if coords else None,
|
| 479 |
+
is_stop=True,
|
| 480 |
+
is_place=False,
|
| 481 |
+
stop_names=(stop,),
|
| 482 |
+
)
|
| 483 |
+
)
|
| 484 |
+
return candidats
|
| 485 |
+
|
| 486 |
+
def _noeud_au_lieu_marche(self, node: Node, access: AccessPoint) -> bool:
|
| 487 |
+
"""Vrai si l'arrêt de ce nœud est bien celui vers lequel on a marché.
|
| 488 |
+
|
| 489 |
+
Une marche (distance > 0) est mesurée depuis la position générale de
|
| 490 |
+
l'arrêt. Si la ligne place son arrêt du même nom à plus de
|
| 491 |
+
MAX_ECART_HOMONYME_M de là, c'est un homonyme lointain : on n'y monte
|
| 492 |
+
pas et on n'y descend pas. Un arrêt pris tel quel (marche nulle, nom
|
| 493 |
+
dit par l'usager) n'est pas concerné.
|
| 494 |
+
"""
|
| 495 |
+
|
| 496 |
+
if access.walk.distance_m <= 0:
|
| 497 |
+
return True
|
| 498 |
+
stop = self.network.stop_for(node)
|
| 499 |
+
general = self.network.coords(stop)
|
| 500 |
+
sur_ligne = self.network.position_on_line(self.network.line_for(node), node.index)
|
| 501 |
+
if general is None or sur_ligne is None:
|
| 502 |
+
return True
|
| 503 |
+
return haversine_m(general, sur_ligne) <= MAX_ECART_HOMONYME_M
|
| 504 |
+
|
| 505 |
+
def _endpoint_map(
|
| 506 |
+
self,
|
| 507 |
+
candidates: list[PlaceCandidate],
|
| 508 |
+
kind: str,
|
| 509 |
+
include_nearby: bool = True,
|
| 510 |
+
nearby_stop_ok: Callable[[str], bool] | None = None,
|
| 511 |
+
) -> dict[str, AccessPoint]:
|
| 512 |
+
result: dict[str, AccessPoint] = {}
|
| 513 |
+
for candidate in candidates:
|
| 514 |
+
for point in self._access_points(
|
| 515 |
+
candidate, kind, include_nearby, nearby_stop_ok
|
| 516 |
+
):
|
| 517 |
+
current = result.get(point.stop)
|
| 518 |
+
if current is None or point.walk.minutes < current.walk.minutes:
|
| 519 |
+
result[point.stop] = point
|
| 520 |
+
return result
|
| 521 |
+
|
| 522 |
+
@staticmethod
|
| 523 |
+
def _is_downtown_endpoint(
|
| 524 |
+
candidates: list[PlaceCandidate],
|
| 525 |
+
coords: tuple[float, float] | None,
|
| 526 |
+
centre: tuple[float, float] | None,
|
| 527 |
+
) -> bool:
|
| 528 |
+
if any(candidate.normalized in DOWNTOWN_STOP_NAMES for candidate in candidates):
|
| 529 |
+
return True
|
| 530 |
+
if centre is not None and coords is not None:
|
| 531 |
+
return haversine_m(coords, centre) <= DOWNTOWN_RADIUS_M
|
| 532 |
+
return False
|
| 533 |
+
|
| 534 |
+
# ------------------------------------------------------------------
|
| 535 |
+
# Public API.
|
| 536 |
+
# ------------------------------------------------------------------
|
| 537 |
+
def find_trips(
|
| 538 |
+
self,
|
| 539 |
+
origin: str,
|
| 540 |
+
destination: str,
|
| 541 |
+
max_trips: int = 3,
|
| 542 |
+
operator: str | None = None,
|
| 543 |
+
first_line: LineKey | None = None,
|
| 544 |
+
origin_place: ResolvedPlace | None = None,
|
| 545 |
+
destination_place: ResolvedPlace | None = None,
|
| 546 |
+
nearby_stop_ok: Callable[[str], bool] | None = None,
|
| 547 |
+
direct_only: bool = False,
|
| 548 |
+
) -> list[Trip]:
|
| 549 |
+
"""Les meilleurs trajets. ``origin_place`` et ``destination_place``
|
| 550 |
+
remplacent la recherche par nom quand l'appelant a déjà résolu le lieu ;
|
| 551 |
+
``nearby_stop_ok`` dit quels arrêts peuvent servir d'arrêt « proche » ;
|
| 552 |
+
``direct_only`` se limite aux bus directs entre les arrêts demandés.
|
| 553 |
+
"""
|
| 554 |
+
|
| 555 |
+
max_trips = max(1, max_trips)
|
| 556 |
+
origin_matches = (
|
| 557 |
+
self._candidates_for(origin_place)
|
| 558 |
+
if origin_place is not None
|
| 559 |
+
else prefer_exact_matches(self.place_index.match(origin), origin)
|
| 560 |
+
)
|
| 561 |
+
if not origin_matches:
|
| 562 |
+
raise PlaceNotFoundError(origin, self.place_index.suggestions(origin))
|
| 563 |
+
|
| 564 |
+
destination_matches = (
|
| 565 |
+
self._candidates_for(destination_place)
|
| 566 |
+
if destination_place is not None
|
| 567 |
+
else prefer_exact_matches(
|
| 568 |
+
self.place_index.match(destination), destination
|
| 569 |
+
)
|
| 570 |
+
)
|
| 571 |
+
if not destination_matches:
|
| 572 |
+
raise PlaceNotFoundError(
|
| 573 |
+
destination, self.place_index.suggestions(destination)
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
origin_points = self._endpoint_map(
|
| 577 |
+
origin_matches, "access", include_nearby=False
|
| 578 |
+
)
|
| 579 |
+
destination_points = self._endpoint_map(
|
| 580 |
+
destination_matches, "egress", include_nearby=False
|
| 581 |
+
)
|
| 582 |
+
expanded_origin_points = self._endpoint_map(
|
| 583 |
+
origin_matches, "access", nearby_stop_ok=nearby_stop_ok
|
| 584 |
+
)
|
| 585 |
+
expanded_destination_points = self._endpoint_map(
|
| 586 |
+
destination_matches, "egress", nearby_stop_ok=nearby_stop_ok
|
| 587 |
+
)
|
| 588 |
+
if not expanded_origin_points:
|
| 589 |
+
raise PlaceNotFoundError(origin, self.place_index.suggestions(origin))
|
| 590 |
+
if not expanded_destination_points:
|
| 591 |
+
raise PlaceNotFoundError(
|
| 592 |
+
destination, self.place_index.suggestions(destination)
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
origin_coords = (origin_place and origin_place.coords) or (
|
| 596 |
+
representative_coordinates(origin_matches)
|
| 597 |
+
)
|
| 598 |
+
destination_coords = (destination_place and destination_place.coords) or (
|
| 599 |
+
representative_coordinates(destination_matches)
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
# La marche peut battre le bus sur les courtes distances. On garde
|
| 603 |
+
# ce trajet à part : il ne remplace le bus que s'il est plus rapide.
|
| 604 |
+
walk_trip: Trip | None = None
|
| 605 |
+
if origin_coords is not None and destination_coords is not None:
|
| 606 |
+
walk_time = walking_minutes(origin_coords, destination_coords)
|
| 607 |
+
if walk_time <= MAX_WALK_ONLY_MINUTES:
|
| 608 |
+
straight = haversine_m(origin_coords, destination_coords)
|
| 609 |
+
walk_distance = straight * WALK_DETOUR_FACTOR
|
| 610 |
+
walk_trip = Trip(
|
| 611 |
+
legs=(),
|
| 612 |
+
walks=(
|
| 613 |
+
Walk(
|
| 614 |
+
kind="walk",
|
| 615 |
+
from_place=origin,
|
| 616 |
+
to_place=destination,
|
| 617 |
+
minutes=walk_time,
|
| 618 |
+
distance_m=walk_distance,
|
| 619 |
+
after_leg=0,
|
| 620 |
+
),
|
| 621 |
+
),
|
| 622 |
+
total_minutes=walk_time,
|
| 623 |
+
transfers=0,
|
| 624 |
+
line_combo=(),
|
| 625 |
+
origin_name=origin,
|
| 626 |
+
destination_name=destination,
|
| 627 |
+
total_distance_m=walk_distance,
|
| 628 |
+
straight_line_m=straight,
|
| 629 |
+
detour=False,
|
| 630 |
+
via_downtown=False,
|
| 631 |
+
ridden_stops=(),
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
centre = self.network.downtown_centre
|
| 635 |
+
origin_is_downtown = self._is_downtown_endpoint(
|
| 636 |
+
origin_matches, origin_coords, centre
|
| 637 |
+
)
|
| 638 |
+
destination_is_downtown = self._is_downtown_endpoint(
|
| 639 |
+
destination_matches, destination_coords, centre
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
def search(
|
| 643 |
+
access_points: dict[str, AccessPoint],
|
| 644 |
+
egress_points: dict[str, AccessPoint],
|
| 645 |
+
) -> list[Trip]:
|
| 646 |
+
return self._search(
|
| 647 |
+
origin_points=access_points,
|
| 648 |
+
destination_points=egress_points,
|
| 649 |
+
origin_name=origin,
|
| 650 |
+
destination_name=destination,
|
| 651 |
+
origin_coords=origin_coords,
|
| 652 |
+
destination_coords=destination_coords,
|
| 653 |
+
origin_is_downtown=origin_is_downtown,
|
| 654 |
+
destination_is_downtown=destination_is_downtown,
|
| 655 |
+
max_trips=max_trips,
|
| 656 |
+
operator=operator,
|
| 657 |
+
first_line=first_line,
|
| 658 |
+
# Sans bus trouvé, rien ne bornerait la recherche : la marche le fait.
|
| 659 |
+
score_limit=walk_trip.total_minutes if walk_trip else float("inf"),
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
# Comme v1 : le trajet direct d'abord. S'il existe, inutile de chercher
|
| 663 |
+
# des changements que l'affichage ne proposera pas.
|
| 664 |
+
def direct(
|
| 665 |
+
access_points: dict[str, AccessPoint],
|
| 666 |
+
egress_points: dict[str, AccessPoint],
|
| 667 |
+
) -> list[Trip]:
|
| 668 |
+
return self._direct_trips(
|
| 669 |
+
access_points,
|
| 670 |
+
egress_points,
|
| 671 |
+
operator,
|
| 672 |
+
first_line,
|
| 673 |
+
origin_name=origin,
|
| 674 |
+
destination_name=destination,
|
| 675 |
+
origin_coords=origin_coords,
|
| 676 |
+
destination_coords=destination_coords,
|
| 677 |
+
origin_is_downtown=origin_is_downtown,
|
| 678 |
+
destination_is_downtown=destination_is_downtown,
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
trips = direct(origin_points, destination_points)
|
| 682 |
+
if not trips and not direct_only:
|
| 683 |
+
trips = search(origin_points, destination_points)
|
| 684 |
+
if (
|
| 685 |
+
expanded_origin_points != origin_points
|
| 686 |
+
or expanded_destination_points != destination_points
|
| 687 |
+
):
|
| 688 |
+
# Si la recherche exacte a trouvé, les arrêts proches ne peuvent plus
|
| 689 |
+
# ajouter qu'un bus direct : un changement avec marche serait écarté
|
| 690 |
+
# plus bas. Inutile de refaire toute la recherche (jusqu'à 7 s).
|
| 691 |
+
trips += (
|
| 692 |
+
direct(expanded_origin_points, expanded_destination_points)
|
| 693 |
+
if trips
|
| 694 |
+
else search(expanded_origin_points, expanded_destination_points)
|
| 695 |
+
)
|
| 696 |
+
# L'appelant de ``direct_only`` trie d'abord les arrêts selon ses règles :
|
| 697 |
+
# c'est lui qui applique ensuite ce filtre, sinon un arrêt qu'il écartera
|
| 698 |
+
# pourrait disqualifier les bons.
|
| 699 |
+
if not direct_only:
|
| 700 |
+
trips = keep_sensible_trips(trips)
|
| 701 |
+
|
| 702 |
+
# Un bus direct depuis l'arrêt demandé jusqu'à l'arrêt demandé : aucun
|
| 703 |
+
# voisin à pied ne le remplace. Les arrêts proches ne servent que s'il
|
| 704 |
+
# n'y en a pas.
|
| 705 |
+
if any(
|
| 706 |
+
trip.transfers == 0 and not _has_endpoint_walk(trip) for trip in trips
|
| 707 |
+
):
|
| 708 |
+
trips = [trip for trip in trips if not _has_endpoint_walk(trip)]
|
| 709 |
+
|
| 710 |
+
# The exact stop remains the primary choice. A nearby stop may add a
|
| 711 |
+
# direct option, but it must not replace a normal exact-stop route
|
| 712 |
+
# with a walk plus extra transfers.
|
| 713 |
+
if any(not _has_endpoint_walk(trip) for trip in trips):
|
| 714 |
+
trips = [
|
| 715 |
+
trip
|
| 716 |
+
for trip in trips
|
| 717 |
+
if trip.transfers == 0 or not _has_endpoint_walk(trip)
|
| 718 |
+
]
|
| 719 |
+
|
| 720 |
+
# ``rank_trips`` ne garde que le plus court par ligne : en direct seul, le
|
| 721 |
+
# choix de l'arrêt sur chaque ligne revient à l'appelant.
|
| 722 |
+
result = (
|
| 723 |
+
list(trips)
|
| 724 |
+
if direct_only
|
| 725 |
+
else remove_dominated_trips(rank_trips(trips), self.network)[:max_trips]
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
if walk_trip is not None:
|
| 729 |
+
fastest_bus = min(
|
| 730 |
+
(trip.total_minutes for trip in trips), default=None
|
| 731 |
+
)
|
| 732 |
+
if fastest_bus is None or walk_trip.total_minutes < fastest_bus:
|
| 733 |
+
result = [walk_trip] + result
|
| 734 |
+
result = result[:max_trips]
|
| 735 |
+
|
| 736 |
+
if not result:
|
| 737 |
+
raise NoRouteFoundError(
|
| 738 |
+
f"No bus trip found between {origin!r} and {destination!r}."
|
| 739 |
+
)
|
| 740 |
+
return result
|
| 741 |
+
|
| 742 |
+
# ------------------------------------------------------------------
|
| 743 |
+
# Search.
|
| 744 |
+
# ------------------------------------------------------------------
|
| 745 |
+
@staticmethod
|
| 746 |
+
def _start_label(stop: str, access: AccessPoint, node: Node) -> _Label:
|
| 747 |
+
access_step = _Step(
|
| 748 |
+
kind="access",
|
| 749 |
+
from_stop=access.walk.from_place,
|
| 750 |
+
to_stop=stop,
|
| 751 |
+
minutes=access.walk.minutes,
|
| 752 |
+
line=node.line,
|
| 753 |
+
direction=node.direction,
|
| 754 |
+
from_index=None,
|
| 755 |
+
to_index=node.index,
|
| 756 |
+
walk_minutes=access.walk.minutes,
|
| 757 |
+
walk_distance_m=access.walk.distance_m,
|
| 758 |
+
)
|
| 759 |
+
return _Label(
|
| 760 |
+
node=node,
|
| 761 |
+
transfers=0,
|
| 762 |
+
cost=access.walk.minutes,
|
| 763 |
+
combo=(node.line,),
|
| 764 |
+
steps=(access_step,),
|
| 765 |
+
rode_since_transfer=False,
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
def _direct_trips(
|
| 769 |
+
self,
|
| 770 |
+
origin_points: dict[str, AccessPoint],
|
| 771 |
+
destination_points: dict[str, AccessPoint],
|
| 772 |
+
operator: str | None,
|
| 773 |
+
first_line: LineKey | None,
|
| 774 |
+
**contexte,
|
| 775 |
+
) -> list[Trip]:
|
| 776 |
+
"""Tous les bus directs entre ces arrêts, en suivant simplement chaque ligne.
|
| 777 |
+
|
| 778 |
+
À part de la recherche par score : un direct lent ne doit pas être perdu
|
| 779 |
+
derrière des trajets à changements. Tata 54 fait Keur Massar -> UCAD sans
|
| 780 |
+
changement, et l'usager le préfère à trois bus plus courts sur la carte.
|
| 781 |
+
"""
|
| 782 |
+
|
| 783 |
+
trips: list[Trip] = []
|
| 784 |
+
for stop, access in origin_points.items():
|
| 785 |
+
for node in self.network.nodes_at_stop(stop):
|
| 786 |
+
if first_line is not None and node.line != first_line:
|
| 787 |
+
continue
|
| 788 |
+
if operator is not None and node.line[0] != operator:
|
| 789 |
+
continue
|
| 790 |
+
if not self._noeud_au_lieu_marche(node, access):
|
| 791 |
+
continue
|
| 792 |
+
label = self._start_label(stop, access, node)
|
| 793 |
+
while True:
|
| 794 |
+
ride = next(
|
| 795 |
+
(
|
| 796 |
+
edge
|
| 797 |
+
for edge in self.network.adjacency[label.node]
|
| 798 |
+
if edge.kind == "ride"
|
| 799 |
+
),
|
| 800 |
+
None,
|
| 801 |
+
)
|
| 802 |
+
if ride is None:
|
| 803 |
+
break
|
| 804 |
+
label = self._advance_ride(label, ride)
|
| 805 |
+
destination = destination_points.get(
|
| 806 |
+
self.network.stop_for(label.node)
|
| 807 |
+
)
|
| 808 |
+
if destination is not None and self._noeud_au_lieu_marche(
|
| 809 |
+
label.node, destination
|
| 810 |
+
):
|
| 811 |
+
trips.append(
|
| 812 |
+
self._build_trip(
|
| 813 |
+
label=label, destination=destination, **contexte
|
| 814 |
+
)
|
| 815 |
+
)
|
| 816 |
+
return trips
|
| 817 |
+
|
| 818 |
+
def _search(
|
| 819 |
+
self,
|
| 820 |
+
origin_points: dict[str, AccessPoint],
|
| 821 |
+
destination_points: dict[str, AccessPoint],
|
| 822 |
+
origin_name: str,
|
| 823 |
+
destination_name: str,
|
| 824 |
+
origin_coords: tuple[float, float] | None,
|
| 825 |
+
destination_coords: tuple[float, float] | None,
|
| 826 |
+
origin_is_downtown: bool,
|
| 827 |
+
destination_is_downtown: bool,
|
| 828 |
+
max_trips: int,
|
| 829 |
+
operator: str | None = None,
|
| 830 |
+
first_line: LineKey | None = None,
|
| 831 |
+
score_limit: float = float("inf"),
|
| 832 |
+
) -> list[Trip]:
|
| 833 |
+
queue: list[tuple[float, int, float, int, _Label]] = []
|
| 834 |
+
counter = itertools.count()
|
| 835 |
+
best_score = score_limit
|
| 836 |
+
|
| 837 |
+
# Recherche guidée (A*) : le temps minimal restant, à vol d'oiseau, s'ajoute à
|
| 838 |
+
# la priorité. Sans cela, 72 000 correspondances font explorer toute la ville
|
| 839 |
+
# avant d'avancer vers l'arrivée (jusqu'à 44 s par requête).
|
| 840 |
+
goals = [
|
| 841 |
+
coords
|
| 842 |
+
for stop in destination_points
|
| 843 |
+
if (coords := self.network.coords(stop)) is not None
|
| 844 |
+
]
|
| 845 |
+
remaining_by_stop: dict[str, float] = {}
|
| 846 |
+
|
| 847 |
+
def remaining(node: Node) -> float:
|
| 848 |
+
stop = self.network.stop_for(node)
|
| 849 |
+
value = remaining_by_stop.get(stop)
|
| 850 |
+
if value is None:
|
| 851 |
+
here = self.network.coords(stop)
|
| 852 |
+
value = (
|
| 853 |
+
min(haversine_m(here, goal) for goal in goals)
|
| 854 |
+
/ BUS_SPEED_M_PER_MIN
|
| 855 |
+
if here is not None and goals
|
| 856 |
+
else 0.0
|
| 857 |
+
)
|
| 858 |
+
remaining_by_stop[stop] = value
|
| 859 |
+
return value
|
| 860 |
+
|
| 861 |
+
best: dict[tuple[Node, int], list[_Label]] = defaultdict(list)
|
| 862 |
+
recorded: dict[tuple[LineKey, ...], Trip] = {}
|
| 863 |
+
accepted: list[Trip] = []
|
| 864 |
+
|
| 865 |
+
for stop, access in origin_points.items():
|
| 866 |
+
for node in self.network.nodes_at_stop(stop):
|
| 867 |
+
if first_line is not None and node.line != first_line:
|
| 868 |
+
continue
|
| 869 |
+
if operator is not None and node.line[0] != operator:
|
| 870 |
+
continue
|
| 871 |
+
if not self._noeud_au_lieu_marche(node, access):
|
| 872 |
+
continue
|
| 873 |
+
self._push(
|
| 874 |
+
queue, best, counter, self._start_label(stop, access, node), remaining
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
expansions = 0
|
| 878 |
+
while queue:
|
| 879 |
+
score_so_far, _, _, _, label = heapq.heappop(queue)
|
| 880 |
+
state = (label.node, label.transfers)
|
| 881 |
+
if not any(existing is label for existing in best[state]):
|
| 882 |
+
continue
|
| 883 |
+
|
| 884 |
+
expansions += 1
|
| 885 |
+
if expansions > MAX_EXPANSIONS:
|
| 886 |
+
break
|
| 887 |
+
if score_so_far >= best_score + MAX_SCORE_ABOVE_BEST:
|
| 888 |
+
break
|
| 889 |
+
|
| 890 |
+
# Queue order is score order, so this lower bound is final.
|
| 891 |
+
if len(accepted) >= max_trips:
|
| 892 |
+
worst_score = max(trip.score for trip in accepted)
|
| 893 |
+
if score_so_far >= worst_score:
|
| 894 |
+
break
|
| 895 |
+
|
| 896 |
+
stop = self.network.stop_for(label.node)
|
| 897 |
+
destination = destination_points.get(stop)
|
| 898 |
+
if (
|
| 899 |
+
destination is not None
|
| 900 |
+
and label.rode_since_transfer
|
| 901 |
+
and self._noeud_au_lieu_marche(label.node, destination)
|
| 902 |
+
):
|
| 903 |
+
trip = self._build_trip(
|
| 904 |
+
label=label,
|
| 905 |
+
destination=destination,
|
| 906 |
+
origin_name=origin_name,
|
| 907 |
+
destination_name=destination_name,
|
| 908 |
+
origin_coords=origin_coords,
|
| 909 |
+
destination_coords=destination_coords,
|
| 910 |
+
origin_is_downtown=origin_is_downtown,
|
| 911 |
+
destination_is_downtown=destination_is_downtown,
|
| 912 |
+
)
|
| 913 |
+
best_score = min(best_score, trip.score)
|
| 914 |
+
current = recorded.get(trip.line_combo)
|
| 915 |
+
if current is None or self._trip_rank(trip) < self._trip_rank(current):
|
| 916 |
+
recorded[trip.line_combo] = trip
|
| 917 |
+
|
| 918 |
+
if not trip.via_downtown:
|
| 919 |
+
accepted.append(trip)
|
| 920 |
+
accepted = self._best_accepted(accepted, max_trips)
|
| 921 |
+
|
| 922 |
+
for edge in self.network.adjacency[label.node]:
|
| 923 |
+
if edge.kind == "ride":
|
| 924 |
+
self._push(
|
| 925 |
+
queue,
|
| 926 |
+
best,
|
| 927 |
+
counter,
|
| 928 |
+
self._advance_ride(label, edge),
|
| 929 |
+
remaining,
|
| 930 |
+
)
|
| 931 |
+
else:
|
| 932 |
+
if label.transfers >= MAX_TRANSFERS:
|
| 933 |
+
continue
|
| 934 |
+
if not label.rode_since_transfer:
|
| 935 |
+
continue
|
| 936 |
+
if operator is not None and edge.target.line[0] != operator:
|
| 937 |
+
continue
|
| 938 |
+
if edge.target.line in label.combo:
|
| 939 |
+
continue
|
| 940 |
+
self._push(
|
| 941 |
+
queue,
|
| 942 |
+
best,
|
| 943 |
+
counter,
|
| 944 |
+
self._advance_transfer(label, edge),
|
| 945 |
+
remaining,
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
return list(recorded.values())
|
| 949 |
+
|
| 950 |
+
@staticmethod
|
| 951 |
+
def _trip_rank(
|
| 952 |
+
trip: Trip,
|
| 953 |
+
) -> tuple[bool, bool, float, int, float, float]:
|
| 954 |
+
# Prefer a clean trip over a detour, and a non-downtown trip over a
|
| 955 |
+
# downtown shortcut, even if the clean version is slightly slower.
|
| 956 |
+
score, minutes, distance, transfers = _rank_key(trip)
|
| 957 |
+
return (
|
| 958 |
+
trip.detour,
|
| 959 |
+
trip.via_downtown,
|
| 960 |
+
score,
|
| 961 |
+
transfers,
|
| 962 |
+
minutes,
|
| 963 |
+
distance,
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
@staticmethod
|
| 967 |
+
def _best_accepted(trips: list[Trip], max_trips: int) -> list[Trip]:
|
| 968 |
+
unique: dict[tuple[LineKey, ...], Trip] = {}
|
| 969 |
+
for trip in trips:
|
| 970 |
+
current = unique.get(trip.line_combo)
|
| 971 |
+
if current is None or _rank_key(trip) < _rank_key(current):
|
| 972 |
+
unique[trip.line_combo] = trip
|
| 973 |
+
|
| 974 |
+
if not unique:
|
| 975 |
+
return []
|
| 976 |
+
limit = _slowest_sensible(
|
| 977 |
+
min(trip.total_minutes for trip in unique.values())
|
| 978 |
+
)
|
| 979 |
+
reasonable = [
|
| 980 |
+
trip for trip in unique.values() if trip.total_minutes <= limit
|
| 981 |
+
]
|
| 982 |
+
return rank_trips(reasonable, max_trips)
|
| 983 |
+
|
| 984 |
+
def _push(
|
| 985 |
+
self,
|
| 986 |
+
queue: list[tuple[float, int, float, int, _Label]],
|
| 987 |
+
best: dict[tuple[Node, int], list[_Label]],
|
| 988 |
+
counter,
|
| 989 |
+
label: _Label,
|
| 990 |
+
remaining: Callable[[Node], float],
|
| 991 |
+
) -> None:
|
| 992 |
+
state = (label.node, label.transfers)
|
| 993 |
+
current = best[state]
|
| 994 |
+
|
| 995 |
+
# A state can be reached with different line combinations. Keep
|
| 996 |
+
# a small set of them, but never keep the same combination twice.
|
| 997 |
+
for existing in list(current):
|
| 998 |
+
if (
|
| 999 |
+
existing.combo == label.combo
|
| 1000 |
+
and existing.rode_since_transfer == label.rode_since_transfer
|
| 1001 |
+
):
|
| 1002 |
+
if existing.cost <= label.cost + 1e-9:
|
| 1003 |
+
return
|
| 1004 |
+
current.remove(existing)
|
| 1005 |
+
|
| 1006 |
+
current.append(label)
|
| 1007 |
+
current.sort(key=lambda item: item.cost)
|
| 1008 |
+
if len(current) > MAX_LABELS_PER_STATE:
|
| 1009 |
+
del current[MAX_LABELS_PER_STATE:]
|
| 1010 |
+
|
| 1011 |
+
heapq.heappush(
|
| 1012 |
+
queue,
|
| 1013 |
+
(
|
| 1014 |
+
label.cost
|
| 1015 |
+
+ TRANSFER_SCORE_MINUTES * label.transfers
|
| 1016 |
+
+ remaining(label.node),
|
| 1017 |
+
label.transfers,
|
| 1018 |
+
label.cost,
|
| 1019 |
+
next(counter),
|
| 1020 |
+
label,
|
| 1021 |
+
),
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
def _advance_ride(self, label: _Label, edge: Edge) -> _Label:
|
| 1025 |
+
from_stop = self.network.stop_for(label.node)
|
| 1026 |
+
to_stop = self.network.stop_for(edge.target)
|
| 1027 |
+
step = _Step(
|
| 1028 |
+
kind="ride",
|
| 1029 |
+
from_stop=from_stop,
|
| 1030 |
+
to_stop=to_stop,
|
| 1031 |
+
minutes=edge.minutes,
|
| 1032 |
+
line=label.node.line,
|
| 1033 |
+
direction=label.node.direction,
|
| 1034 |
+
from_index=label.node.index,
|
| 1035 |
+
to_index=edge.target.index,
|
| 1036 |
+
distance_m=edge.distance_m,
|
| 1037 |
+
estimated=edge.estimated,
|
| 1038 |
+
)
|
| 1039 |
+
return _Label(
|
| 1040 |
+
node=edge.target,
|
| 1041 |
+
transfers=label.transfers,
|
| 1042 |
+
cost=label.cost + edge.minutes,
|
| 1043 |
+
combo=label.combo,
|
| 1044 |
+
steps=label.steps + (step,),
|
| 1045 |
+
rode_since_transfer=True,
|
| 1046 |
+
)
|
| 1047 |
+
|
| 1048 |
+
def _advance_transfer(self, label: _Label, edge: Edge) -> _Label:
|
| 1049 |
+
from_stop = self.network.stop_for(label.node)
|
| 1050 |
+
to_stop = self.network.stop_for(edge.target)
|
| 1051 |
+
step = _Step(
|
| 1052 |
+
kind="transfer",
|
| 1053 |
+
from_stop=from_stop,
|
| 1054 |
+
to_stop=to_stop,
|
| 1055 |
+
minutes=edge.minutes,
|
| 1056 |
+
line=edge.target.line,
|
| 1057 |
+
direction=edge.target.direction,
|
| 1058 |
+
from_index=label.node.index,
|
| 1059 |
+
to_index=edge.target.index,
|
| 1060 |
+
walk_minutes=edge.walk_minutes,
|
| 1061 |
+
walk_distance_m=edge.walk_distance_m,
|
| 1062 |
+
transfer_penalty=edge.transfer_penalty,
|
| 1063 |
+
)
|
| 1064 |
+
return _Label(
|
| 1065 |
+
node=edge.target,
|
| 1066 |
+
transfers=label.transfers + 1,
|
| 1067 |
+
cost=label.cost + edge.minutes,
|
| 1068 |
+
combo=label.combo + (edge.target.line,),
|
| 1069 |
+
steps=label.steps + (step,),
|
| 1070 |
+
rode_since_transfer=False,
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
# ------------------------------------------------------------------
|
| 1074 |
+
# Turning a search label into a friendly Trip.
|
| 1075 |
+
# ------------------------------------------------------------------
|
| 1076 |
+
def _build_trip(
|
| 1077 |
+
self,
|
| 1078 |
+
label: _Label,
|
| 1079 |
+
destination: AccessPoint,
|
| 1080 |
+
origin_name: str,
|
| 1081 |
+
destination_name: str,
|
| 1082 |
+
origin_coords: tuple[float, float] | None,
|
| 1083 |
+
destination_coords: tuple[float, float] | None,
|
| 1084 |
+
origin_is_downtown: bool,
|
| 1085 |
+
destination_is_downtown: bool,
|
| 1086 |
+
) -> Trip:
|
| 1087 |
+
alight_stop = self.network.stop_for(label.node)
|
| 1088 |
+
egress_step = _Step(
|
| 1089 |
+
kind="egress",
|
| 1090 |
+
from_stop=alight_stop,
|
| 1091 |
+
to_stop=destination.walk.to_place,
|
| 1092 |
+
minutes=destination.walk.minutes,
|
| 1093 |
+
line=label.node.line,
|
| 1094 |
+
direction=label.node.direction,
|
| 1095 |
+
from_index=label.node.index,
|
| 1096 |
+
to_index=None,
|
| 1097 |
+
walk_minutes=destination.walk.minutes,
|
| 1098 |
+
walk_distance_m=destination.walk.distance_m,
|
| 1099 |
+
)
|
| 1100 |
+
steps = label.steps + (egress_step,)
|
| 1101 |
+
|
| 1102 |
+
legs: list[Leg] = []
|
| 1103 |
+
walks: list[Walk] = []
|
| 1104 |
+
ridden_stops: list[str] = []
|
| 1105 |
+
current: dict | None = None
|
| 1106 |
+
minimum_leg_extra = 0.0
|
| 1107 |
+
|
| 1108 |
+
def finish_leg() -> None:
|
| 1109 |
+
nonlocal current, minimum_leg_extra
|
| 1110 |
+
if current is None:
|
| 1111 |
+
return
|
| 1112 |
+
line = self.network.lines[current["line"]]
|
| 1113 |
+
billed_minutes = max(MIN_LEG_MINUTES, current["minutes"])
|
| 1114 |
+
minimum_leg_extra += billed_minutes - current["minutes"]
|
| 1115 |
+
legs.append(
|
| 1116 |
+
Leg(
|
| 1117 |
+
operator=line.company,
|
| 1118 |
+
line=line.name,
|
| 1119 |
+
board_stop=current["board_stop"],
|
| 1120 |
+
alight_stop=current["alight_stop"],
|
| 1121 |
+
direction=line.terminus_for(current["direction"]),
|
| 1122 |
+
num_stops=abs(
|
| 1123 |
+
int(current["end_index"]) - int(current["start_index"])
|
| 1124 |
+
),
|
| 1125 |
+
minutes=billed_minutes,
|
| 1126 |
+
distance_m=current["distance"],
|
| 1127 |
+
estimated=current["estimated"],
|
| 1128 |
+
board_index=line.index_in_list(current["direction"], int(current["start_index"])),
|
| 1129 |
+
alight_index=line.index_in_list(current["direction"], int(current["end_index"])),
|
| 1130 |
+
)
|
| 1131 |
+
)
|
| 1132 |
+
current = None
|
| 1133 |
+
|
| 1134 |
+
for step in steps:
|
| 1135 |
+
if step.kind == "access":
|
| 1136 |
+
if step.walk_minutes > 0 or (step.walk_distance_m or 0) > 0:
|
| 1137 |
+
walks.append(
|
| 1138 |
+
Walk(
|
| 1139 |
+
kind="access",
|
| 1140 |
+
from_place=step.from_stop,
|
| 1141 |
+
to_place=step.to_stop,
|
| 1142 |
+
minutes=step.walk_minutes,
|
| 1143 |
+
distance_m=step.walk_distance_m,
|
| 1144 |
+
after_leg=0,
|
| 1145 |
+
)
|
| 1146 |
+
)
|
| 1147 |
+
elif step.kind == "ride":
|
| 1148 |
+
if (
|
| 1149 |
+
current is None
|
| 1150 |
+
or current["line"] != step.line
|
| 1151 |
+
or current["direction"] != step.direction
|
| 1152 |
+
):
|
| 1153 |
+
finish_leg()
|
| 1154 |
+
current = {
|
| 1155 |
+
"line": step.line,
|
| 1156 |
+
"direction": step.direction,
|
| 1157 |
+
"board_stop": step.from_stop,
|
| 1158 |
+
"alight_stop": step.to_stop,
|
| 1159 |
+
"start_index": step.from_index,
|
| 1160 |
+
"end_index": step.to_index,
|
| 1161 |
+
"minutes": step.minutes,
|
| 1162 |
+
"distance": step.distance_m,
|
| 1163 |
+
"estimated": step.estimated,
|
| 1164 |
+
}
|
| 1165 |
+
else:
|
| 1166 |
+
current["alight_stop"] = step.to_stop
|
| 1167 |
+
current["end_index"] = step.to_index
|
| 1168 |
+
current["minutes"] += step.minutes
|
| 1169 |
+
current["estimated"] = current["estimated"] or step.estimated
|
| 1170 |
+
if (
|
| 1171 |
+
current["distance"] is None
|
| 1172 |
+
or step.distance_m is None
|
| 1173 |
+
):
|
| 1174 |
+
current["distance"] = None
|
| 1175 |
+
else:
|
| 1176 |
+
current["distance"] += step.distance_m
|
| 1177 |
+
for stop in (step.from_stop, step.to_stop):
|
| 1178 |
+
if not ridden_stops or ridden_stops[-1] != stop:
|
| 1179 |
+
ridden_stops.append(stop)
|
| 1180 |
+
elif step.kind == "transfer":
|
| 1181 |
+
finish_leg()
|
| 1182 |
+
if step.walk_minutes > 0 or (step.walk_distance_m or 0) > 0:
|
| 1183 |
+
walks.append(
|
| 1184 |
+
Walk(
|
| 1185 |
+
kind="transfer",
|
| 1186 |
+
from_place=step.from_stop,
|
| 1187 |
+
to_place=step.to_stop,
|
| 1188 |
+
minutes=step.walk_minutes,
|
| 1189 |
+
distance_m=step.walk_distance_m,
|
| 1190 |
+
after_leg=len(legs),
|
| 1191 |
+
)
|
| 1192 |
+
)
|
| 1193 |
+
elif step.kind == "egress":
|
| 1194 |
+
finish_leg()
|
| 1195 |
+
if step.walk_minutes > 0 or (step.walk_distance_m or 0) > 0:
|
| 1196 |
+
walks.append(
|
| 1197 |
+
Walk(
|
| 1198 |
+
kind="egress",
|
| 1199 |
+
from_place=step.from_stop,
|
| 1200 |
+
to_place=step.to_stop,
|
| 1201 |
+
minutes=step.walk_minutes,
|
| 1202 |
+
distance_m=step.walk_distance_m,
|
| 1203 |
+
after_leg=len(legs),
|
| 1204 |
+
)
|
| 1205 |
+
)
|
| 1206 |
+
|
| 1207 |
+
finish_leg()
|
| 1208 |
+
|
| 1209 |
+
total_minutes = sum(step.minutes for step in steps) + minimum_leg_extra
|
| 1210 |
+
|
| 1211 |
+
total_distance: float | None = 0.0
|
| 1212 |
+
for step in steps:
|
| 1213 |
+
if step.kind == "ride":
|
| 1214 |
+
if step.distance_m is None:
|
| 1215 |
+
total_distance = None
|
| 1216 |
+
break
|
| 1217 |
+
total_distance += step.distance_m
|
| 1218 |
+
else:
|
| 1219 |
+
total_distance += step.walk_distance_m or 0.0
|
| 1220 |
+
|
| 1221 |
+
straight_line: float | None = None
|
| 1222 |
+
if origin_coords is not None and destination_coords is not None:
|
| 1223 |
+
straight_line = haversine_m(origin_coords, destination_coords)
|
| 1224 |
+
|
| 1225 |
+
detour = bool(
|
| 1226 |
+
total_distance is not None
|
| 1227 |
+
and straight_line is not None
|
| 1228 |
+
and total_distance > DETOUR_LIMIT * straight_line
|
| 1229 |
+
)
|
| 1230 |
+
via_downtown = self._passes_downtown(
|
| 1231 |
+
ridden_stops,
|
| 1232 |
+
origin_is_downtown=origin_is_downtown,
|
| 1233 |
+
destination_is_downtown=destination_is_downtown,
|
| 1234 |
+
)
|
| 1235 |
+
|
| 1236 |
+
return Trip(
|
| 1237 |
+
legs=tuple(legs),
|
| 1238 |
+
walks=tuple(walks),
|
| 1239 |
+
total_minutes=total_minutes,
|
| 1240 |
+
transfers=label.transfers,
|
| 1241 |
+
line_combo=label.combo,
|
| 1242 |
+
origin_name=origin_name,
|
| 1243 |
+
destination_name=destination_name,
|
| 1244 |
+
total_distance_m=total_distance,
|
| 1245 |
+
straight_line_m=straight_line,
|
| 1246 |
+
detour=detour,
|
| 1247 |
+
via_downtown=via_downtown,
|
| 1248 |
+
ridden_stops=tuple(ridden_stops),
|
| 1249 |
+
estimated=any(leg.estimated for leg in legs),
|
| 1250 |
+
)
|
| 1251 |
+
|
| 1252 |
+
def _passes_downtown(
|
| 1253 |
+
self,
|
| 1254 |
+
ridden_stops: list[str],
|
| 1255 |
+
origin_is_downtown: bool,
|
| 1256 |
+
destination_is_downtown: bool,
|
| 1257 |
+
) -> bool:
|
| 1258 |
+
if origin_is_downtown or destination_is_downtown:
|
| 1259 |
+
return False
|
| 1260 |
+
|
| 1261 |
+
if any(normalize_name(stop) in DOWNTOWN_STOP_NAMES for stop in ridden_stops):
|
| 1262 |
+
return True
|
| 1263 |
+
|
| 1264 |
+
centre = self.network.downtown_centre
|
| 1265 |
+
if centre is None:
|
| 1266 |
+
return False
|
| 1267 |
+
for stop in ridden_stops:
|
| 1268 |
+
coords = self.network.coords(stop)
|
| 1269 |
+
if coords is not None and haversine_m(coords, centre) <= DOWNTOWN_RADIUS_M:
|
| 1270 |
+
return True
|
| 1271 |
+
return False
|