01 The principle: nothing made up

When I opened Lille, I set myself a rule: every criterion must come from a public dataset that I can cite. If a source is missing, the criterion is not offered, rather than being estimated by guesswork.

The whole city is produced by a single Django command, import_ilevia, which I can rerun at any time. It takes three downloaded files (the GTFS, the turnstile counts and the list of train stations), queries two APIs, cross-references everything and writes a data file, lille/stations.json, which the game loads into the database on each deployment.

BASH
make import-lille   # downloads, then: manage.py import_ilevia ilevia-gtfs.zip ilevia-entrees-metro.csv gares-de-voyageurs.csv
make load-stations  # loads the file into the city of Lille

The result: 2 lines, 60 stations, and about fifty playable criteria.

02 The sources

Source Publisher License What I take from it
GTFS of the Ilévia network Métropole européenne de Lille, via data.gouv.fr Licence ouverte 2.0 (Open License 2.0) Lines, colors, station order, platforms and their coordinates, tram stops
French Wikipedia (MediaWiki API) Wikimedia CC BY-SA 4.0 Station name, opening year, level
Administrative divisions API (Découpage administratif, geo.api.gouv.fr) Etalab Licence ouverte The commune of each station
Passenger stations (Gares de voyageurs) SNCF ODbL Position of the train stations, for train connections
Entries and exits of metro stations (Flux des entrées et sorties des stations de métro) Ilévia, via the Métropole européenne de Lille Licence ouverte 2.0 Entries of each station, hour by hour, for ridership

The GTFS is the format that transit networks publish for trip-planning apps: an archive of CSV files. routes.txt describes the lines, stops.txt the stops and their coordinates, trips.txt each trip, and stop_times.txt, the biggest, each passage of each train at each stop. It is my backbone.

03 The GTFS format

Here are the two metro lines in routes.txt, among hundreds of bus lines:

TEXT
route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color
ME1,ILE,M1,METRO LIGNE 1,CHU EURASANTÉ <> 4 CANTONS STADE P MAUROY,1,,FDC41F,000000
ME2,ILE,M2,METRO LIGNE 2,SAINT PHILIBERT <> C.H. DRON,1,,E30613,FFFFFF

route_type gives the mode: 0 for tram, 1 for metro, 3 for bus. In stops.txt, a station is a stop area (location_type 1) that groups its accesses and its platforms (location_type 0), linked by parent_station:

TEXT
stop_id,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url,location_type,parent_station,stop_timezone,wheelchair_boarding
920,Gare Lille Flandres,GARE LILLE FLANDRES 59000 LILLE,50.637779,3.070865,1,,1,,,0
LIG011,Gare Lille Flandres,59000 LILLE -,50.636405,3.071141,1,,0,920,,1
LIG115,Gare Lille Flandres,RUE DES CANONIERS 59000 LILLE - AU DROIT DE LA PL ST HUBERT,50.638408,3.070733,1,,0,920,,1

And stop_times.txt, the biggest file in the archive, gives each passage: a trip (trip_id), a stop, its rank in the trip.

TEXT
trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled,timepoint,stop_time_desc
5440172,05:30:00,05:30:00,4CR001,1,,0,0,,,
5440172,05:32:00,05:32:00,RCT002,2,,0,0,,,

The direction of each trip (direction_id, 0 or 1) and its line are in trips.txt.

04 From the GTFS to the stations

I read the archive without unpacking it onto the disk, with Python's zipfile module. The metro lines are those with route_type 1: M1 and M2 become line 1 (#FDC41F, black text) and line 2 (#E30613, white text). I only keep the trips of these lines and of the tram, then I go through stop_times.txt just once, as a stream, to rebuild the sequence of stops of each trip:

PYTHON
with zipfile.ZipFile(path) as archive:
    routes = {r["route_id"]: r for r in _rows(archive, "routes.txt")}
    metro = {
        rid: r["route_short_name"].removeprefix("M")
        for rid, r in routes.items()
        if r["route_type"] == METRO_ROUTE_TYPE
    }
    tram = {rid for rid, r in routes.items() if r["route_type"] == TRAM_ROUTE_TYPE}
    trips = {
        t["trip_id"]: (t["route_id"], t["direction_id"])
        for t in _rows(archive, "trips.txt")
        if t["route_id"] in metro or t["route_id"] in tram
    }
    ...
    trip_stops: dict[str, list[tuple[int, str]]] = defaultdict(list)
    for row in _rows(archive, "stop_times.txt"):  # a big file: streamed once
        if row["trip_id"] in trips:
            trip_stops[row["trip_id"]].append((int(row["stop_sequence"]), row["stop_id"]))

The passages of a trip are not necessarily sorted in the file: I sort them by stop_sequence, then I count how many trips run each sequence of names, per line and per direction. The longest sequence in direction 0 gives the line. The others must be pieces of it, otherwise the command stops:

PYTHON
def main_path(
    code: str, sequences: Mapping[tuple[str, str], Counter[tuple[str, ...]]]
) -> list[str]:
    ours = sequences[code, "0"]
    if not ours:
        raise CommandError(f"Line {code}: no trip in direction 0.")
    main = max(ours, key=lambda sequence: (len(sequence), ours[sequence]))
    if len(set(main)) != len(main):
        raise CommandError(f"Line {code}: a station twice in its longest trip.")
    for direction in ("0", "1"):
        for sequence in sequences[code, direction]:
            if not set(sequence) <= set(main):
                extra = sorted(set(sequence) - set(main))
                raise CommandError(f"Line {code}: a trip serves {extra}, off its main path.")
    return list(main)

Lille's lines have no forks, only partial services. If one of them ever had one, the import would stop instead of producing a wrong line: that's on purpose.

A station, in the GTFS, is several platforms: one per direction, sometimes one per line. I group them by name, and the station's position is the average of its platforms. Gare Lille-Flandres and Porte des Postes, served by both lines, thus count as one station each: 18 + 44 − 2 = 60. The terminuses are read at the two ends of each path.

05 Wikipedia, stitched together by geography

The GTFS says nothing about history. For the opening year and the level, I query Wikipedia's MediaWiki API in two steps. First, the list of articles in each category, "Station de la ligne 1 du métro de Lille" and "… ligne 2 …":

TEXT
GET https://fr.wikipedia.org/w/api.php?action=query&list=categorymembers
    &cmtitle=Catégorie:Station de la ligne 1 du métro de Lille&cmlimit=100&format=json&formatversion=2

Then their wikitext, the raw source of the articles, in batches of 20 titles separated by | (prop=revisions&rvprop=content). Each call identifies itself with a User-Agent, as Wikimedia asks, and a 429 or 5xx response is retried after a pause, the one from the Retry-After header when the server gives one.

What interests me is the infobox, at the top of the article. Here is the one for Rihour, shortened:

TEXT
{{Infobox Station de métro
 | nom                   = Rihour
 | ville                 = [[Lille]]
 | latitude              = 50.63551389
 | longitude             = 3.062902778
 | position              = Souterrain
 | quais                 = 2
 | mise en service       = {{date|25|avril|1983}}
 | exploitant            = [[Ilévia]]

Wikitext has no guaranteed structure, but the fields of an infobox always follow the form | key = value, one per line. A regular expression is enough:

PYTHON
def infobox_field(wikitext: str, key: str) -> str:
    found = re.search(rf"^\s*\|\s*{re.escape(key)}\s*=[ \t]*(.*)$", wikitext, re.MULTILINE)
    return found.group(1).strip() if found else ""

The year is the smallest 19xx or 20xx number found in mise en service (service start): an interchange station lists one date per line there, and the {{date|25|avril|1983}} template doesn't need to be interpreted.

PYTHON
years = [
    int(y) for y in re.findall(r"\b(?:19|20)\d{2}\b", infobox_field(wikitext, "mise en service"))
]
if not years:
    raise CommandError(f"{title}: no opening year in its infobox.")

The position field is free text ("Souterrain", "Aérienne", "En surface"…), which I reduce to three levels:

PYTHON
def level_of(position: str) -> Level:
    text = normalize(position)
    if text.startswith("aerien"):
        return "aerienne"
    if "surface" in text:
        return "fleur_de_sol"
    if text.startswith("souterrain") or "tranchee" in text:
        # An open cut ("En tranchée ouverte": Croix-Paquet in Lyon) is below the ground.
        return "souterraine"
    raise ValueError(f"unknown position {position!r}")

An unknown value makes the import fail rather than pass silently. The same function is used for Lyon.

What's left is to know which article is about which station. Names are not enough: the GTFS and Wikipedia don't spell them the same way. So I match by distance: all (station, article) pairs are sorted from the closest to the farthest, and associated in that order, only once each, within 300 m. It is a greedy matching: it doesn't look for the global optimum, but on a network where stations are several hundred meters apart, the closest pair is always the right one.

PYTHON
pairs = sorted(
    (haversine(lat, lon, article.lat, article.lon), name, article.title)
    for name, (lat, lon) in centres.items()
    for article in articles
    if article.lat is not None and article.lon is not None
)
matched: dict[str, Article] = {}
used: set[str] = set()
for distance, name, title in pairs:
    if distance <= ARTICLE_RADIUS and name not in matched and title not in used:
        matched[name] = by_title[title]
        used.add(title)
left_stations = sorted(set(centres) - matched.keys())
left_articles = sorted(a.title for a in articles if a.title not in used)
if len(left_stations) == len(left_articles) == 1:
    matched[left_stations[0]] = by_title[left_articles[0]]
elif left_stations or left_articles:
    raise CommandError(f"Unmatched stations {left_stations}, unmatched articles {left_articles}")

haversine gives the as-the-crow-flies distance on the Earth's sphere. An article with no coordinates takes the last remaining station, if only one is left on each side; anything else left over makes the import fail.

The name displayed in the game is the article's title without its "(métro de Lille)" suffix, not the GTFS one: that's why you read "Gare Lille-Flandres" or "Cité Scientifique - Professeur Gabillard".

For an interchange station, the year kept is the oldest. I also compared with Wikidata (property P1619, opening date): both sources give the same years, except for Jean-Jaurès, which Wikidata dates to 1989 by mistake. It opened in 1999, with the extension of line 2.

Years What opens
1982 – 1984 Line 1, first to Villeneuve-d'Ascq
1989 Line 2, as far as Saint-Philibert
1994 Gare Lille-Europe, with the TGV
1995 – 2000 The extensions of line 2 toward Roubaix and Tourcoing

06 The commune, down to the coordinate

For the commune, I query the Découpage administratif (administrative divisions) API with the position of each station, asking only for the two useful fields:

TEXT
GET https://geo.api.gouv.fr/communes?lat=50.6355&lon=3.0629&fields=nom,codeDepartement&format=json
[{"nom": "Lille", "codeDepartement": "59"}]

The API returns the commune that contains this point. The 60 calls go out on 6 parallel threads, with up to 5 retries and a growing wait when the API answers 429 (too many requests) or 5xx.

A subtlety: Lomme and Hellemmes are communes associated with Lille, so the API files them under Lille. Only Pont Supérieur and Lomme - Lambersart - Arthur-Notebart fall on the Lambersart side.

Commune Stations
Lille 29
Tourcoing 9
Villeneuve-d'Ascq 7
Roubaix 6
Mons-en-Barœul 3
Lambersart, Croix, Wasquehal 2 each

07 Tram and train

A station has a tram connection (the Mongy, route_type 0) if one of its platforms shares a parent_station with a tram stop in the GTFS, or if it is within 150 m of a stop. Five stations qualify, including Eurotéléport and Wasquehal - Pavé de Lille.

For the train, I cross-reference with SNCF's list of passenger stations, a semicolon-separated CSV whose position fits in a single column, latitude and longitude separated by a comma:

TEXT
nom;libellecourt;segment_drg;position_geographique;codeinsee;codes_uic;id
Lille Flandres;LLF;A;50.636577, 3.06987;59350;87286005;2df9f83c-36e9-48f3-b6a5-4bd45aeb91fe
PYTHON
with path.open(encoding="utf-8-sig", newline="") as f:
    for row in csv.DictReader(f, delimiter=";"):
        if row["position_geographique"]:
            lat, lon = (float(part) for part in row["position_geographique"].split(","))
            gares.append((row["nom"], lat, lon))

The utf-8-sig encoding removes the BOM, that invisible character some exports put at the start of a file and which would otherwise stick to the name of the first column. But SNCF's point is not always where I expect it: Tourcoing's is 385 m from the Gare de Tourcoing station. Hence two rules, distance or name:

PYTHON
connected = set()
for name, points in gtfs.platforms.items():
    station = normalize(names[name])
    for gare, lat, lon in gares:
        near = any(haversine(p.lat, p.lon, lat, lon) <= TRAIN_CONNECTION_RADIUS for p in points)
        named = station.startswith("gare ") and normalize(gare) in station
        if near or named:
            connected.add(name)

normalize removes accents, case and punctuation before comparing. Six stations qualify in total, from Pont de Bois to Gare Jean-Lebas Roubaix.

08 Ridership, at the turnstiles

This is the source that arrived last. Ilévia publishes, station by station and hour by hour, the number of passages counted at the turnstiles, entries and exits separately, from September 2025 to October 2026: more than 560,000 rows. The dataset is served by the Métropole's WFS, which returns everything as a single CSV of about 45 MB, with no key or pagination, if you ask only for the useful columns:

TEXT
FID,objectid,date_jour,heure_debut,libelle_station,code_arret_commercial,nombre_entree_heure,code_ligne
entree_sortie_metro.3882324,3882324,2025-09-23,2025-09-23T08:00:00,Gare Lille Flandres,920,1771,ME1

That Tuesday, between 8 and 9 a.m., 1,771 passengers entered at Gare Lille Flandres. Three choices turn these rows into one figure per station:

  • Entries only. This is RATP's definition of incoming traffic, the one behind Paris's figures: a passenger counts once, where they board.
  • Not the hours from 1 to 5 a.m. Ilévia warns that what is counted there comes from maintenance operations, not passengers.
  • An average per counted day. Each station has between 364 and 398 days of measurements: dividing by its own days avoids penalizing those that had gaps.
PYTHON
totals: Counter[str] = Counter()
days: defaultdict[str, set[str]] = defaultdict(set)
for row in csv.DictReader(f):
    station, day = row["libelle_station"].strip(), row["date_jour"].strip()
    days[station].add(day)
    if int(row["heure_debut"][11:13]) not in MAINTENANCE_HOURS:
        totals[station] += int(row["nombre_entree_heure"])
ridership = {station: round(totals[station] / len(days[station])) for station in days}

The columns are read by name, and an unreadable value stops the import rather than counting as zero.

Shorter names

Ilévia names its stations as on the platforms, shorter than Wikipedia: 52 of the 60 match once accents, case and punctuation are removed, and the other 8 go through a hand-written table.

PYTHON
RIDERSHIP_ALIASES = {
    "Alsace": "Alsace - Plaine Images",
    "CHU - Centre O. Lambret": "CHU - Centre Oscar-Lambret",
    "Canteleu": "Canteleu - Euratechnologies",
    "Caulier": "Madeleine Caulier",
    "Cité Scientifique": "Cité Scientifique - Professeur Gabillard",
    "Lomme-Lambersart": "Lomme - Lambersart - Arthur-Notebart",
    "Porte de Douai": "Porte de Douai - Jardin des Plantes",
    "Quatre Cantons": "Quatre Cantons - Stade Pierre-Mauroy",
}

As with the geography, the import refuses to guess: an Ilévia name with no station, or a station with no figure, stops it and names them. If Ilévia renames a station, I'll know at the next import.

What the figures say

Busiest Passengers per day Least busy Passengers per day
Gare Lille-Flandres 44,315 Bourgogne 992
Porte des Postes 13,702 Mercure 1,105
République - Beaux-Arts 12,294 Carliers 1,321
Rihour 10,214 Mitterie 1,484
Porte de Douai - Jardin des Plantes 9,878 Wasquehal - Hôtel de Ville 1,486

Gare Lille-Flandres crushes everything else: more than three times the second. Its figure is that of the whole station, both lines and the tram's share included, because no turnstile knows which train the passenger will take; Ilévia estimates that tram share at 10%. Porte des Postes, the other two-line station, is second. At the bottom of the table, it's line 2: 12 of the 13 stations under 2,000 passengers per day are its own, including 5 in Tourcoing, at the end of the line, and 4 at the other end, on the Lomme and Lambersart side. Square Flandres is the only one on line 1. The median station gets about 3,400 passengers per day.

Two thresholds, in gaps

Lille's ridership criteria are more than 8,000 passengers per day (9 stations) and fewer than 2,000 (13 stations). Each threshold falls in a gap in the distribution: the last station above 8,000, Gambetta, has 8,276, and the next one, Villeneuve-d'Ascq - Hôtel de Ville, 7,769; under 2,000, Pont de Neuville has 1,914, and the next one, Gare de Tourcoing, 2,179. The stations closest to each threshold are 3 or 4% away from it: a small variation in the counts wouldn't make a station switch sides.

Lille's figures are per day, Paris's are per year: they live in two separate fields, and the criterion's value names the city (lille-8000), so that no criterion row mixes the two. Answer rarity reads only Paris's annual figures: in Lille, all stations keep the same weight, interchanges aside.

09 The criteria that come out

A criterion is only playable if it has at least 2 stations and at most 70% of the network: beyond that, it no longer separates anything. That's the case for line 2, which serves 44 stations out of 60: it isn't a criterion, it would be a gift.

Family Criteria Source
Network Line 1, terminus, tram connection, train connection GTFS, SNCF
Place Commune, elevated station Administrative divisions API, Wikipedia
History Opened before 1984, 1989 or 1999; since 1995, 1999 or 2000 Wikipedia
History More than 8,000 or fewer than 2,000 passengers per day Ilévia counts
Name Letters, start and end of the name, words like "Porte" or "Mairie", length The name itself

Criteria are shared between cities in the database: a criterion row is unique by type and by value. Lille's train connection has the empty value, Lyon's has lyon, Toulouse's has toulouse, so that each city has its own text.

10 What's missing, and why

Several Paris criteria don't exist in Lille, for lack of a source:

  • The origin of names, nearby places, trivia: in Paris, they come from station-by-station lists. None exists yet for Lille.
  • The automatic metro. The whole VAL is driverless: the criterion would be true everywhere, it wouldn't separate anything.

If you know an open source that fills one of these gaps, the criteria ideas page is made for that.

11 Thanks

Thanks to Florent Berault, of the Métropole européenne de Lille, for the file of ridership by station he sent me, which became Lille's ridership criteria.