Spaces:
Running on Zero

PythonMindset commited on
Commit
8811ad3
·
verified ·
1 Parent(s): cda2a9a

Deploiement GuindiMa AI (interface Gradio) (part 2)

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