Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ recursive-include c2corg_api *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.ma
graft c2corg_api/emails/
recursive-include c2corg_api/search/es_mappings *.json
recursive-include c2corg_api/partners/regions *.json
include c2corg_api/itinevert/school_holidays.json
2 changes: 2 additions & 0 deletions c2corg_api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
feeds,
health,
history,
itinevert,
misc,
navitia,
openapi,
Expand Down Expand Up @@ -129,6 +130,7 @@ def create_fastapi_app(settings, registry=None):
misc.include(app)
users.include(app)
navitia.include(app)
itinevert.include(app)
avalanche_bulletins.include(app)
partner_outings.include(app)
user_actions.include(app)
Expand Down
16 changes: 16 additions & 0 deletions c2corg_api/itinevert/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""The search of the routes reachable by public transport (Itinevert).

A search starts from a transport hub of a town (a Navitia stop area), on a
class of days (the timetables repeat: kind of day x period). Two Navitia
`journeys` requests without destination / without origin give, for the whole
day, the earliest arrival at and the latest departure from every stop point
reachable; joined with the stop areas linked to the access waypoints, they
give the time on site of each waypoint and route.

The modules are plain functions, without database or Navitia calls, except
the ones of `search` which bind them together:
- `reachability`: the answers of Navitia reduced to the stop times, and the
time on site of the waypoints and routes;
- `day_classes`: the class of days of a date;
- `hubs`: the transport hubs of a town.
"""
175 changes: 175 additions & 0 deletions c2corg_api/itinevert/day_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
"""The class of days of a date: the dates of a class share their timetables.

A class is a kind of day (weekday, Saturday, Sunday or bank holiday) in a
period: a school holiday period of the zone of the origin, or a season out of
the holidays. The classes are also cut at the yearly change of the timetables
(the second Sunday of December), so that a search computed before the change
is not used after it.

The school holidays are in school_holidays.json (see
scripts/itinevert/update_school_holidays.py).
"""

import json
import pathlib
from dataclasses import dataclass
from datetime import date, timedelta
from functools import cache

WEEKDAY = 'weekday'
SATURDAY = 'saturday'
SUNDAY = 'sunday' # and bank holidays

SEASONS = {
12: 'winter',
1: 'winter',
2: 'winter',
3: 'spring',
4: 'spring',
5: 'spring',
6: 'summer',
7: 'summer',
8: 'summer',
9: 'autumn',
10: 'autumn',
11: 'autumn',
}

# the school holiday zone of each department (the academies of 2026)
_ZONE_DEPARTMENTS = {
# Besançon, Bordeaux, Clermont-Ferrand, Dijon, Grenoble, Limoges, Lyon,
# Poitiers
'A': '25 39 70 90 24 33 40 47 64 03 15 43 63 21 58 71 89 07 26 38 73 74 '
'19 23 87 01 42 69 16 17 79 86',
# Aix-Marseille, Amiens, Lille, Nancy-Metz, Nantes, Nice, Normandie,
# Orléans-Tours, Reims, Rennes, Strasbourg
'B': '04 05 13 84 02 60 80 59 62 54 55 57 88 44 49 53 72 85 06 83 14 27 '
'50 61 76 18 28 36 37 41 45 08 10 51 52 22 29 35 56 67 68',
# Créteil, Montpellier, Paris, Toulouse, Versailles
'C': '77 93 94 11 30 34 48 66 75 09 12 31 32 46 65 81 82 78 91 92 95',
'corsica': '2A 2B',
}
ZONES = {
department: zone
for zone, departments in _ZONE_DEPARTMENTS.items()
for department in departments.split()
}
# Alsace-Moselle has two more bank holidays
_ALSACE_MOSELLE = {'57', '67', '68'}


def department(insee: str | None) -> str | None:
"""Return the department of the INSEE code of a town."""
if not insee or len(insee) != 5:
return None
return insee[:3] if insee.startswith('97') else insee[:2]


def zone(insee: str | None) -> str | None:
"""Return the school holiday zone of a town, None out of France."""
return ZONES.get(department(insee))


def easter(year: int) -> date:
"""Return the Easter Sunday of a year (anonymous Gregorian algorithm)."""
a, b, c = year % 19, year // 100, year % 100
d, e = b // 4, b % 4
f = (b + 8) // 25
g = (b - f + 1) // 3
h = (19 * a + b - d - g + 15) % 30
i, k = c // 4, c % 4
m = (32 + 2 * e + 2 * i - h - k) % 7
n = (a + 11 * h + 22 * m) // 451
month, day = divmod(h + m - 7 * n + 114, 31)
return date(year, month, day + 1)


@cache
def bank_holidays(year: int, alsace_moselle: bool = False) -> frozenset[date]:
sunday = easter(year)
days = {
date(year, 1, 1),
sunday + timedelta(days=1),
date(year, 5, 1),
date(year, 5, 8),
sunday + timedelta(days=39),
sunday + timedelta(days=50),
date(year, 7, 14),
date(year, 8, 15),
date(year, 11, 1),
date(year, 11, 11),
date(year, 12, 25),
}
if alsace_moselle:
days |= {sunday - timedelta(days=2), date(year, 12, 26)}
return frozenset(days)


def timetable_change(year: int) -> date:
"""Return the yearly change of the timetables: the 2nd Sunday of December."""
first = date(year, 12, 1)
return first + timedelta(days=(6 - first.weekday()) % 7 + 7)


def timetable_year(day: date) -> int:
"""Return the year of the timetables of a day.

The timetables starting in December of a year are the ones of the next
year.
"""
return day.year + 1 if day >= timetable_change(day.year) else day.year


@cache
def _school_holidays() -> dict[str, list[tuple[str, date, date]]]:
path = pathlib.Path(__file__).with_name('school_holidays.json')
raw = json.loads(path.read_text(encoding='utf-8'))
return {
z: [
(name, date.fromisoformat(s), date.fromisoformat(e))
for name, s, e in periods
]
for z, periods in raw.items()
}


def holiday_period(day: date, holiday_zone: str | None):
"""Return the school holiday period of a day: (name, first day), or None."""
for name, start, end in _school_holidays().get(holiday_zone, ()):
if start <= day < end:
return name, start
return None


def kind_of_day(day: date, insee: str | None = None) -> str:
alsace_moselle = department(insee) in _ALSACE_MOSELLE
if day.weekday() == 6 or day in bank_holidays(day.year, alsace_moselle):
return SUNDAY
return SATURDAY if day.weekday() == 5 else WEEKDAY


@dataclass(frozen=True)
class DayClass:
"""The class of days of a date: its key names the cache of a search."""

timetable_year: int
period: str
kind: str

@property
def key(self) -> str:
return f'{self.timetable_year}:{self.period}:{self.kind}'


def day_class(day: date, insee: str | None = None) -> DayClass:
"""Return the class of days of a date, for an origin in the town `insee`.

A holiday period is named by its first day: the same period of another
year is another class. Out of the holidays, the season.
"""
holidays = holiday_period(day, zone(insee))
if holidays:
period = f'{holidays[0]}-{holidays[1].isoformat()}'
else:
period = SEASONS[day.month]
return DayClass(timetable_year(day), period, kind_of_day(day, insee))
144 changes: 144 additions & 0 deletions c2corg_api/itinevert/hubs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""The transport hubs of a town: where a search starts from.

A town does not start from its centre on foot (what Navitia does for an
administrative region without main stop areas), but from the stop areas where
the most lines stop, of all modes. They are found in the answer of Navitia's
`coords/{lon;lat}/stop_areas?depth=3` (the stop areas around the centre of
the town with their lines), first with the stop areas served by more than
buses (HUB_MODES), then, for a small town without any, with all of them.

The stop areas of a hub (the train station, the bus station beside it...) are
grouped when closer than GROUP_RADIUS. The hubs of at least MIN_LINES lines
are proposed, at most MAX_HUBS, always at least the best one.
"""

from dataclasses import dataclass, field

from c2corg_api.itinevert.reachability import distance

# more than 10 lines
MIN_LINES = 11
MAX_HUBS = 6
GROUP_RADIUS = 200 # meters
# the radius around the centre of the town
SEARCH_RADIUS = 4000 # meters
# the physical modes of the hubs: the stop areas served by buses only are
# fetched for a town without any of these
HUB_MODES = (
'Train',
'LocalTrain',
'LongDistanceTrain',
'RapidTransit',
'Metro',
'Tramway',
'Coach',
'Funicular',
)


def hub_modes_filter() -> str:
"""Return the Navitia filter of the stop areas served by a HUB_MODES mode."""
return ' or '.join(f'physical_mode.id=physical_mode:{mode}' for mode in HUB_MODES)


@dataclass
class Hub:
# the stop area of the hub with the most lines: the origin of a search
stop_area_id: str
name: str
lon: float
lat: float
lines: int
# the number of lines per physical mode
modes: dict[str, int] = field(default_factory=dict)
stop_area_ids: list[str] = field(default_factory=list)
# from the centre of the town
distance: float = 0

def to_dict(self):
return {
'id': self.stop_area_id,
'name': self.name,
'lon': self.lon,
'lat': self.lat,
'lines': self.lines,
'modes': self.modes,
}


def _in_town(stop_area, insee):
return any(
admin.get('insee') == insee
for admin in stop_area.get('administrative_regions', [])
)


def _coord(stop_area):
return float(stop_area['coord']['lon']), float(stop_area['coord']['lat'])


def rank_hubs(
stop_areas: list[dict], insee: str, centre: tuple[float, float]
) -> list[Hub]:
"""Return the hubs of a town from the stop areas of a Navitia answer.

The most lines first, the closest to the centre first on a tie.
"""
in_town = [s for s in stop_areas if _in_town(s, insee) and 'coord' in s]

# the groups of stop areas closer than GROUP_RADIUS to one another
parent = list(range(len(in_town)))

def root(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i

coords = [_coord(s) for s in in_town]
for i in range(len(in_town)):
for j in range(i):
if distance(*coords[i], *coords[j]) < GROUP_RADIUS:
parent[root(i)] = root(j)
groups: dict[int, list[int]] = {}
for i in range(len(in_town)):
groups.setdefault(root(i), []).append(i)

hubs = []
for members in groups.values():
lines = {}
for i in members:
for line in in_town[i].get('lines', []):
lines[line['id']] = line
modes: dict[str, int] = {}
for line in lines.values():
for mode in line.get('physical_modes', []):
modes[mode['name']] = modes.get(mode['name'], 0) + 1
best = max(members, key=lambda i: len(in_town[i].get('lines', [])))
lon, lat = coords[best]
hubs.append(
Hub(
stop_area_id=in_town[best]['id'],
name=in_town[best]['name'],
lon=lon,
lat=lat,
lines=len(lines),
modes=modes,
stop_area_ids=[in_town[i]['id'] for i in members],
distance=distance(lon, lat, *centre),
)
)
hubs.sort(key=lambda h: (-h.lines, h.distance))
return hubs


def select_hubs(
hubs: list[Hub], min_lines: int = MIN_LINES, max_hubs: int = MAX_HUBS
) -> list[Hub]:
"""Return the hubs proposed.

At least min_lines lines, at most max_hubs, at least the best one when
there is one.
"""
selected = [h for h in hubs if h.lines >= min_lines][:max_hubs]
return selected or hubs[:1]
Loading