nemobi 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. nemobi/__init__.py +9 -0
  2. nemobi/__main__.py +4 -0
  3. nemobi/cerema/__init__.py +26 -0
  4. nemobi/cerema/common.py +76 -0
  5. nemobi/cerema/deplacements.py +254 -0
  6. nemobi/cerema/edgt.py +254 -0
  7. nemobi/cerema/edvm.py +269 -0
  8. nemobi/cerema/emc2.py +141 -0
  9. nemobi/cerema/emd.py +128 -0
  10. nemobi/cerema/menages.py +391 -0
  11. nemobi/cerema/nantes_opendata.py +207 -0
  12. nemobi/cerema/personnes.py +532 -0
  13. nemobi/cerema/reader.py +160 -0
  14. nemobi/cerema/survey.py +451 -0
  15. nemobi/cerema/trajets.py +423 -0
  16. nemobi/cerema/zones.py +406 -0
  17. nemobi/classes.py +341 -0
  18. nemobi/cli.py +103 -0
  19. nemobi/common/__init__.py +1 -0
  20. nemobi/common/cars.py +119 -0
  21. nemobi/common/clean.py +559 -0
  22. nemobi/common/households.py +99 -0
  23. nemobi/common/legs.py +134 -0
  24. nemobi/common/motorcycles.py +41 -0
  25. nemobi/common/persons.py +180 -0
  26. nemobi/common/trips.py +265 -0
  27. nemobi/common/zones.py +37 -0
  28. nemobi/egt2010/__init__.py +1 -0
  29. nemobi/egt2010/deplacements.py +227 -0
  30. nemobi/egt2010/menages.py +403 -0
  31. nemobi/egt2010/personnes.py +350 -0
  32. nemobi/egt2010/survey.py +92 -0
  33. nemobi/egt2010/trajets.py +231 -0
  34. nemobi/egt2010/zones.py +11 -0
  35. nemobi/egt2020/__init__.py +1 -0
  36. nemobi/egt2020/deplacements.py +203 -0
  37. nemobi/egt2020/menages.py +168 -0
  38. nemobi/egt2020/motos.py +98 -0
  39. nemobi/egt2020/personnes.py +405 -0
  40. nemobi/egt2020/survey.py +94 -0
  41. nemobi/egt2020/trajets.py +347 -0
  42. nemobi/egt2020/voitures.py +131 -0
  43. nemobi/emg2023/__init__.py +1 -0
  44. nemobi/emg2023/deplacements.py +255 -0
  45. nemobi/emg2023/menages.py +24 -0
  46. nemobi/emg2023/personnes.py +170 -0
  47. nemobi/emg2023/survey.py +66 -0
  48. nemobi/emp/__init__.py +1 -0
  49. nemobi/emp/common.py +31 -0
  50. nemobi/emp/deplacements.py +403 -0
  51. nemobi/emp/menages.py +190 -0
  52. nemobi/emp/motos.py +105 -0
  53. nemobi/emp/personnes.py +657 -0
  54. nemobi/emp/survey.py +110 -0
  55. nemobi/emp/voitures.py +184 -0
  56. nemobi/logger.py +26 -0
  57. nemobi/main.py +257 -0
  58. nemobi/resources/__init__.py +42 -0
  59. nemobi/resources/admin_express.py +96 -0
  60. nemobi/resources/insee_data.py +446 -0
  61. nemobi/resources/nuts.py +132 -0
  62. nemobi/schema/__init__.py +12 -0
  63. nemobi/schema/cars.py +95 -0
  64. nemobi/schema/common.py +165 -0
  65. nemobi/schema/guarantees.py +735 -0
  66. nemobi/schema/households.py +183 -0
  67. nemobi/schema/legs.py +277 -0
  68. nemobi/schema/motorcycles.py +70 -0
  69. nemobi/schema/persons.py +897 -0
  70. nemobi/schema/trips.py +484 -0
  71. nemobi/utils.py +275 -0
  72. nemobi/validation.py +795 -0
  73. nemobi-2.0.0.dist-info/METADATA +256 -0
  74. nemobi-2.0.0.dist-info/RECORD +78 -0
  75. nemobi-2.0.0.dist-info/WHEEL +5 -0
  76. nemobi-2.0.0.dist-info/entry_points.txt +2 -0
  77. nemobi-2.0.0.dist-info/licenses/LICENSE.md +7 -0
  78. nemobi-2.0.0.dist-info/top_level.txt +1 -0
nemobi/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ from importlib.metadata import version
2
+
3
+ from .classes import SurveyDataReader as SurveyDataReader
4
+ from .classes import read_many as read_many
5
+ from .logger import setup as setup
6
+ from .main import bulk_standardize as bulk_standardize
7
+ from .main import standardize as standardize
8
+
9
+ __version__ = version("nemobi")
nemobi/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ if __name__ == "__main__":
2
+ from .cli import app
3
+
4
+ app()
@@ -0,0 +1,26 @@
1
+ from pathlib import Path
2
+ from zipfile import ZipFile
3
+
4
+ from .edgt import EDGTReader
5
+ from .edvm import EDVMReader
6
+ from .emc2 import EMC2Reader
7
+ from .emd import EMDReader
8
+ from .nantes_opendata import OpenDataReader
9
+
10
+
11
+ def standardize(
12
+ source: Path | ZipFile, survey_type: str, skip_spatial: bool = False, skip_insee: bool = False
13
+ ):
14
+ if survey_type == "EMC2":
15
+ reader = EMC2Reader(source)
16
+ elif survey_type == "EDGT":
17
+ reader = EDGTReader(source)
18
+ elif survey_type == "EDGT-opendata":
19
+ reader = OpenDataReader(source)
20
+ elif survey_type == "EDVM":
21
+ reader = EDVMReader(source)
22
+ elif survey_type == "EMD":
23
+ reader = EMDReader(source)
24
+ else:
25
+ raise NotImplementedError
26
+ return reader.standardize(skip_spatial, skip_insee)
@@ -0,0 +1,76 @@
1
+ # ruff: noqa: E501
2
+ MODE_MAP = {
3
+ 1: "walking", # Marche à pied.
4
+ 10: "bicycle:driver:traditional:shared", # Conducteur VLS
5
+ 11: "bicycle:driver:traditional", # Conducteur de vélo.
6
+ 12: "bicycle:passenger", # Passager de vélo.
7
+ 13: "motorcycle:driver:moped", # Conducteur de deux ou trois roues motorisés < 50 cm3.
8
+ 14: "motorcycle:passenger:moped", # Passager de deux ou trois roues motorisés < 50 cm3.
9
+ 15: "motorcycle:driver:moto", # Conducteur de deux ou trois roues motorisés >= 50 cm3
10
+ 16: "motorcycle:passenger:moto", # Passager de deux ou trois roues motorisés >= 50 cm3.
11
+ 17: "motorcycle:driver", # Conducteur de deux ou trois roues motorisés (si pas de détail sur la cylindrée).
12
+ 18: "motorcycle:passenger", # Passager de deux ou trois roues motorisés (si pas de détail sur la cylindrée)..
13
+ 21: "car:driver", # Conducteur de véhicule particulier (VP).
14
+ 22: "car:passenger", # Passager de véhicule particulier (VP).
15
+ 31: "public_transit:urban:bus", # Passager bus urbain (réseau ville centre).
16
+ 32: "public_transit:urban:tram", # Passager tramway (réseau ville centre).
17
+ 33: "public_transit:urban:metro", # Passager métro (réseau ville centre).
18
+ 34: "public_transit:urban:funicular", # Note. Not documented. Used in Le Havre (and other surveys?).
19
+ 37: "public_transit:urban:demand_responsive", # Transport à la demande (U ou IU)
20
+ 38: "public_transit:urban", # Passager autres réseaux urbains ds aire enquête.
21
+ 39: "public_transit:urban", # Passager autre réseau urbain hors AE
22
+ 41: "public_transit:urban:coach", # Passager transports interurbains routiers et autres autocars (TER routiers, lignes régulières départementales, scolaires, périscolaires, occasionnel….).
23
+ 42: "public_transit:interurban:coach", # Cars longues distances (Eurolines/Isilines, Ouibus, Flixbus…)).
24
+ 43: "public_transit:interurban:coach", # Passagers autocars anciennes définitions
25
+ 51: "public_transit:interurban:other_train", # Passager Train
26
+ 61: "taxi_or_VTC", # Passager taxi.
27
+ 71: "employer_transport", # Transport employeur (exclusivement)
28
+ 72: "public_transit:school", # For Thionville 2012
29
+ 81: "truck:driver", # Conducteur de fourgon, camionnette, camion (pour tournées professionnelles ou déplacements privés).
30
+ 82: "truck:passenger", # Passager de fourgon, camionnette, camion (pour tournées professionnelles ou déplacements privés)..
31
+ 91: "water_transport", # Transport Fluvial ou maritime.
32
+ 92: "airplane", # Avion.
33
+ 93: "personal_transporter:non_motorized", # Roller, skate, trottinette non électrique
34
+ 94: "wheelchair", # Fauteuil roulant.
35
+ 95: "other", # Autres modes (tracteur, engin agricole, quad, etc.).
36
+ 96: "personal_transporter:motorized", # Petits engins électriques (trottinette, segway, solowheel, etc)
37
+ 97: "personal_transporter:unspecified", # Roller, skate, trottinette électrique ou non (ancien code)
38
+ }
39
+
40
+
41
+ # For the EMC2 surveys, categories 17 and 18 have moved to 19 and 20, while 17 and 18 are now
42
+ # representing electric bicycle.
43
+ # Category 51 as been split from Train (general, interurban) to 4 distinct train modes.
44
+ # Category 61 as been split from taxi (general) to taxi and VTC.
45
+ EMC2_MODE_MAP = MODE_MAP.copy()
46
+ EMC2_MODE_MAP.update(
47
+ {
48
+ 17: "bicycle:driver:electric", # Conducteur de vélo Assistance Electrique
49
+ 18: "bicycle:driver:electric:shared", # Conducteur de vélo Assistance Electrique en Libre Service
50
+ 19: "motorcycle:driver", # Conducteur de deux ou trois roues motorisés (si pas de détail sur la cylindrée).
51
+ 20: "motorcycle:passenger", # Passager de deux ou trois roues motorisés (si pas de détail sur la cylindrée)..
52
+ 51: "public_transit:interurban:TGV", # Passager TGV
53
+ 52: "public_transit:urban:TER", # Passager train TER
54
+ 53: "public_transit:interurban:intercités", # Passagers autres trains (Intercité, TET)
55
+ 54: "public_transit:interurban:other_train", # Passager train non précisé
56
+ 61: "taxi", # Passager taxi.
57
+ 62: "VTC", # Passager VTC
58
+ }
59
+ )
60
+
61
+ # For open-data Nantes, some new modes are defined.
62
+ NANTES_MODE_MAP = MODE_MAP.copy()
63
+ NANTES_MODE_MAP.update(
64
+ {
65
+ 19: "bicycle:driver:traditional:shared", # Conducteur de vélo Libre-Service ou location
66
+ 30: "public_transit:urban:bus", # Passager bus réseau Cap Atlantique
67
+ 34: "public_transit:urban:bus", # Passager bus réseau Nantes TAN (y compris express)
68
+ 35: "public_transit:urban:bus", # Passager Chronobus (C1 à C7) réseau Nantes TAN
69
+ 36: "public_transit:urban:bus", # Passager hélYce BHNS réseau ST Nazaire STRAN
70
+ 37: "public_transit:urban:bus", # Passager bus réseau ST Nazaire STRAN (lignes U urbaines, Ty Bus, C1, SD, Zénibus)
71
+ 38: "public_transit:urban:demand_responsive", # Transport à la demande et PMR (Proxitan à Nantes, Liberty Bus et Ty Bus Taxi à St Nazaire, Lila et Abeille)
72
+ 52: "public_transit:urban:TER", # Passager TER
73
+ 53: "public_transit:interurban:other_train", # Passager autre train (TGV, Corail, InterCités et Grandes Lignes…)
74
+ 73: "public_transit:school", # Passagers transports scolaires (réseau STRAN)
75
+ }
76
+ )
@@ -0,0 +1,254 @@
1
+ # ruff: noqa: E501
2
+ import io
3
+ from pathlib import Path
4
+
5
+ import polars as pl
6
+ from loguru import logger
7
+ from polars.datatypes import DataTypeClass
8
+
9
+ from nemobi.common.trips import clean
10
+ from nemobi.schema.common import CURRENT_YEAR
11
+ from nemobi.utils import detect_csv_delimiter
12
+
13
+ from .reader import CeremaReader
14
+
15
+ SCHEMA: dict[str, DataTypeClass] = {
16
+ "DP1": pl.UInt8, # Code fichier = 3 (déplacement)
17
+ "DMET": pl.UInt8, # Méthode d'enquête du ménage (EMC2 only)
18
+ "IDD3": pl.UInt16, # Année de fin d'enquête
19
+ "IDD4": pl.String, # Code Insee ville centre
20
+ "ZFD": pl.String, # Zone fine de résidence
21
+ "ECH": pl.UInt32, # Numéro d'échantillon
22
+ "PER": pl.UInt8, # Numéro de personne
23
+ "NDEP": pl.UInt8, # Numéro de déplacement
24
+ "GD1": pl.String, # Insee Zone fine du lieu de résidence de la personne concernée par le déplacement
25
+ "STD": pl.String, # Secteur de tirage dans l'enquête d'origine (résidence)
26
+ "D2A": pl.UInt8, # Motif Origine du déplacement
27
+ "D2B": pl.UInt8, # Motif Origine de la personne accompagnée
28
+ "D3": pl.String, # Zone fine Origine du déplacement
29
+ "GDO1": pl.String, # Insee Zone fine Origine du déplacement
30
+ "STDO": pl.String, # Secteur de tirage dans l'enquête d'origine (origine du déplacement)
31
+ "D4": pl.Int32, # Heure de départ du déplacement
32
+ "D5A": pl.UInt8, # Motif Destination du déplacement
33
+ "D5B": pl.UInt8, # Motif Destination de la personne accompagnée
34
+ "D6": pl.UInt8, # Nombre d'arrêts sur la tournée
35
+ "D7": pl.String, # Zone fine Destination du déplacement
36
+ "GDD1": pl.String, # Insee Zone fine Destination du déplacement
37
+ "STDD": pl.String, # Secteur de tirage dans l'enquête d'origine (destination du déplacement)
38
+ "D8": pl.Int32, # Heure d'arrivée du déplacement
39
+ "D9": pl.Int32, # Durée du déplacement
40
+ "D10": pl.UInt8, # Nombre de trajets (en modes mécanisés)
41
+ "D11": pl.Float64, # Longueur à vol d'oiseau
42
+ "D12": pl.Float64, # Distance parcourue
43
+ "MODP": pl.UInt8, # Mode principal
44
+ "TYPD": pl.UInt8, # Type de déplacement
45
+ }
46
+
47
+ PURPOSE_MAP = {
48
+ 1: "home:main", # Domicile (partir de, se rendre à).
49
+ 2: "home:secondary", # Résidence secondaire, logement occasionnel, hôtel, autre domicile (partir de, se rendre à).
50
+ 11: "work:usual", # Travailler sur le lieu d'emploi déclaré.
51
+ 12: "work:telework", # Travailler sur un autre lieu - télétravail.
52
+ 13: "work:secondary", # Travailler sur un autre lieu hors télétravail
53
+ 14: "work:other", # Travailler sur un autre lieu sans distinction
54
+ # NOTE. We discard the information on the exact study location type (middle-school, high-school,
55
+ # etc.) because the information can read from the person characteristics (`student_group`).
56
+ 21: "education:childcare", # Être gardé (Nourrice, crèche...).
57
+ 22: "education:usual", # Étudier sur le lieu d'études déclaré (école maternelle et primaire).
58
+ 23: "education:usual", # Étudier sur le lieu d'études déclaré (collège).
59
+ 24: "education:usual", # Étudier sur le lieu d'études déclaré (lycée).
60
+ 25: "education:usual", # Étudier sur le lieu d'études déclaré (universités et grandes écoles).
61
+ 26: "education:other", # Étudier sur un autre lieu (école maternelle et primaire).
62
+ 27: "education:other", # Étudier sur un autre lieu (collège).
63
+ 28: "education:other", # Étudier sur un autre lieu (lycée).
64
+ 29: "education:other", # Étudier sur un autre lieu (universités et grandes écoles).
65
+ 30: "shopping:no_purchase", # Visite d'un magasin, d'un centre commercial ou d'un marché de plein vent sans effectuer d'achat
66
+ 31: "shopping:unspecified", # Réaliser plusieurs motifs en centre commercial.
67
+ 32: "shopping:unspecified", # Faire des achats en grand magasin, supermarché, hypermarché et leurs galeries marchandes.
68
+ 33: "shopping:unspecified", # Faire des achats en petit et moyen commerce et drive in
69
+ 34: "shopping:unspecified", # Faire des achats en marché couvert et de plein vent.
70
+ 35: "shopping:pickup", # Récupérer des achats faits à distance (Drive, points relais)
71
+ 41: "task:healthcare", # Recevoir des soins (santé).
72
+ 42: "task:procedure", # Faire une démarche autre que rechercher un emploi.
73
+ 43: "task:job_search", # Rechercher un emploi.
74
+ 44: "shopping:pickup", # OPEN DATA NANTES ONLY: RECUPERER UN ACHAT FAIT A DISTANCE (TEL, VPC, INTERNET…)
75
+ 45: "task:procedure", # OPEN DATA NANTES ONLY: FAIRE UNE DEMARCHE AUTRE QUE RECHERCHER UN EMPLOI OU RECUPERER UN ACHAT FAIT A DISTANCE
76
+ 51: "leisure:sport_or_culture", # Participer à des loisirs, des activités sportives, culturelles ou associatives.
77
+ 52: "leisure:walk_or_driving_lesson", # Faire une promenade, du « lèche-vitrines », prendre une leçon de conduite.
78
+ 53: "leisure:restaurant", # Se restaurer hors du domicile.
79
+ 54: "leisure:visiting", # Visiter des parents ou des amis.
80
+ # NOTE. We discard the information on whether the escorted person is present during pick_up /
81
+ # drop_off activity as it can be deduced (when I go pick-up someone, he's not there; when I come
82
+ # back from picking-up someone, he's there). Also, there are some errors in the data (like
83
+ # having the escorted person both before and after picking him up).
84
+ 61: "escort:activity:drop_off", # Accompagner quelqu'un (personne présente).
85
+ 62: "escort:activity:pick_up", # Aller chercher quelqu'un (personne présente).
86
+ 63: "escort:activity:drop_off", # Accompagner quelqu'un (personne absente).
87
+ 64: "escort:activity:pick_up", # Aller chercher quelqu'un (personne absente).
88
+ 68: "escort:unspecified:drop_off", # Accompagner quelqu'un ou déposer quelqu'un à un mode de transport (sans info présence personne)
89
+ 69: "escort:unspecified:pick_up", # Aller chercher quelqu'un ou reprendre quelqu'un à un mode de transport (sans info présence personne)
90
+ 71: "escort:transport:drop_off", # Déposer une personne à un mode de transport (personne présente).
91
+ 72: "escort:transport:pick_up", # Reprendre une personne à un mode de transport (personne présente).
92
+ 73: "escort:transport:drop_off", # Déposer d'une personne à un mode de transport (personne absente).
93
+ 74: "escort:transport:pick_up", # Reprendre une personne à un mode de transport( personne absente).
94
+ 81: "work:professional_tour", # Réaliser une tournée professionnelle.
95
+ 82: "shopping:tour_no_purchase", # Tournée de magasin sans achat
96
+ 91: "other", # Autres motifs
97
+ # 96: "escort:middle_high_school", # Étudier sur le lieu d'études déclaré (collège ou lycée). Cas egt personne accompagnée
98
+ # 97: "escort:middle_high_school:other", # Étudier sur un autre lieu (collège ou lycée). Cas egt personne accompagnée
99
+ # 98: "escort:shopping", # Faire des achats sans précision (egt, motif personne accompagnée)
100
+ # Note: Values 96, 97, and 98 are documented but never appear in a survey.
101
+ }
102
+
103
+ SHOP_TYPE_MAP = {
104
+ 31: "mall", # Réaliser plusieurs motifs en centre commercial.
105
+ 32: "supermarket_or_hypermarket", # Faire des achats en grand magasin, supermarché, hypermarché et leurs galeries marchandes.
106
+ 33: "small_shop", # Faire des achats en petit et moyen commerce et drive in
107
+ 34: "market", # Faire des achats en marché couvert et de plein vent.
108
+ 35: "drive_in", # Récupérer des achats faits à distance (Drive, points relais)
109
+ }
110
+
111
+ TRIP_PERIMETER_MAP = {
112
+ 1: "internal", # interne au périmètre d'enquête
113
+ 2: "crossing", # en échange
114
+ 3: "external", # externe au périmètre d'enquête
115
+ 9: None, # inconnu (cas où origine ou destination inconnue)
116
+ }
117
+
118
+
119
+ def scan_trips_impl(source: Path | io.BytesIO):
120
+ separator = detect_csv_delimiter(source)
121
+ return pl.scan_csv(
122
+ source, separator=separator, schema_overrides=SCHEMA, null_values=["aa", "aaaaa"]
123
+ )
124
+
125
+
126
+ class TripsReader(CeremaReader):
127
+ def scan_trips(self):
128
+ lfs_iter = map(scan_trips_impl, self.trips_filenames())
129
+ lf = pl.concat(lfs_iter, how="vertical")
130
+ lf = lf.sort(self.get_trip_index_cols())
131
+ return lf
132
+
133
+ def standardize_trips(self, skip_insee: bool = False):
134
+ lf = self.scan_trips()
135
+ # Add household_id, person_id, trip date, and trip weekday.
136
+ lf = lf.with_columns(
137
+ original_person_id=pl.struct(**self.get_person_index_cols_from_trips())
138
+ ).join(
139
+ self.persons.select(
140
+ "original_person_id", "person_id", "household_id", "trip_date", "trip_weekday"
141
+ ),
142
+ on="original_person_id",
143
+ how="left",
144
+ coalesce=True,
145
+ maintain_order="left",
146
+ )
147
+ lf = lf.rename(
148
+ {
149
+ "GDO1": "origin_insee",
150
+ "D3": "origin_detailed_zone",
151
+ "STDO": "origin_draw_zone",
152
+ "GDD1": "destination_insee",
153
+ "D7": "destination_detailed_zone",
154
+ "STDD": "destination_draw_zone",
155
+ "D6": "nb_tour_stops",
156
+ }
157
+ )
158
+ lf = lf.with_columns(
159
+ original_trip_id=pl.struct(self.get_trip_index_cols()),
160
+ origin_purpose=pl.col("D2A").replace_strict(PURPOSE_MAP),
161
+ origin_escort_purpose=pl.col("D2B").replace_strict(PURPOSE_MAP),
162
+ origin_shop_type=pl.col("D2A").replace_strict(SHOP_TYPE_MAP, default=None),
163
+ departure_time=60 * (pl.col("D4") // 100) + pl.col("D4") % 100,
164
+ destination_purpose=pl.col("D5A").replace_strict(PURPOSE_MAP),
165
+ destination_escort_purpose=pl.col("D5B").replace_strict(PURPOSE_MAP),
166
+ destination_shop_type=pl.col("D5A").replace_strict(SHOP_TYPE_MAP, default=None),
167
+ arrival_time=60 * (pl.col("D8") // 100) + pl.col("D8") % 100,
168
+ trip_euclidean_distance_km=pl.col("D11") / 1e3,
169
+ trip_travel_distance_km=pl.col("D12") / 1e3,
170
+ main_mode=pl.col("MODP").replace_strict(self.get_mode_map()),
171
+ trip_perimeter=pl.col("TYPD").replace_strict(TRIP_PERIMETER_MAP),
172
+ )
173
+ lf = lf.with_columns(
174
+ # In some cases, the departure and arrival times are switched.
175
+ departure_time=pl.when(
176
+ pl.col("D9") == pl.col("departure_time") - pl.col("arrival_time")
177
+ )
178
+ .then("arrival_time")
179
+ .otherwise("departure_time"),
180
+ arrival_time=pl.when(pl.col("D9") == pl.col("departure_time") - pl.col("arrival_time"))
181
+ .then("departure_time")
182
+ .otherwise("arrival_time"),
183
+ # When destination purpose is 52 (« Faire une promenade, du « lèche-vitrines », prendre
184
+ # une leçon de conduite. ») and `nb_tour_stops` is defined, then we know that purpose is
185
+ # « lèche-vitrines » so we can set purpose to "shopping:tour_no_purchase".
186
+ destination_purpose=pl.when(pl.col("D5A").eq(52), pl.col("nb_tour_stops").is_not_null())
187
+ .then(pl.lit("shopping:tour_no_purchase"))
188
+ .otherwise("destination_purpose"),
189
+ # Special case for Saint-Brieuc 2012: there is no NULL value in the D6 column
190
+ # (nb_tour_stops). It seems that the column represents either the trip travel time or
191
+ # the actual number of tour stops. To be safe, we just throw away all the values.
192
+ nb_tour_stops=pl.when(pl.col("nb_tour_stops").is_not_null().all())
193
+ .then(pl.lit(None))
194
+ .otherwise("nb_tour_stops"),
195
+ # Values 99000, 99999, 99095, 99300 do not represent any known INSEE / country.
196
+ origin_insee=pl.col("origin_insee").replace(["99000", "99999", "99095", "99300"], None),
197
+ destination_insee=pl.col("destination_insee").replace(
198
+ ["99000", "99999", "99095", "99300"], None
199
+ ),
200
+ )
201
+ lf = lf.sort("original_trip_id")
202
+ lf = fix_origin_destination_detailed_zones(lf)
203
+ df = lf.collect()
204
+ # For Besançon 2018, there is one missing person.
205
+ n = df["person_id"].null_count()
206
+ if n > 0:
207
+ logger.warning(f"{n} trips are assigned to an unknown person. They are dropped.")
208
+ df = df.filter(pl.col("person_id").is_not_null())
209
+ self.trips = clean(
210
+ df.lazy(),
211
+ year=self.survey_year() or CURRENT_YEAR,
212
+ special_locations=self.special_locations_coords,
213
+ detailed_zones=self.detailed_zones_coords,
214
+ skip_insee=skip_insee,
215
+ )
216
+ # When the INSEE code ends with "000" or "999" it means "rest of the département".
217
+ # We drop these values because they do not add any additional information compared to `_dep`
218
+ # columns.
219
+ # This is done after the automatic cleaning so that the département is correctly read.
220
+ self.trips = self.trips.with_columns(
221
+ origin_insee=pl.when(
222
+ pl.col("origin_insee").str.ends_with("000")
223
+ | pl.col("origin_insee").str.ends_with("999")
224
+ )
225
+ .then(None)
226
+ .otherwise("origin_insee"),
227
+ destination_insee=pl.when(
228
+ pl.col("destination_insee").str.ends_with("000")
229
+ | pl.col("destination_insee").str.ends_with("999")
230
+ )
231
+ .then(None)
232
+ .otherwise("destination_insee"),
233
+ )
234
+
235
+
236
+ def fix_origin_destination_detailed_zones(lf: pl.LazyFrame):
237
+ # For external origin / destination location, the detailed zone id is sometimes set to
238
+ # "8" + INSEE or "9" + INSEE. In this case, keeping the detailed zone id does not add any
239
+ # information so we set it to NULL.
240
+ lf = lf.with_columns(
241
+ origin_detailed_zone=pl.when("8" + pl.col("origin_insee") == pl.col("origin_detailed_zone"))
242
+ .then(None)
243
+ .when("9" + pl.col("origin_insee") == pl.col("origin_detailed_zone"))
244
+ .then(None)
245
+ .otherwise("origin_detailed_zone"),
246
+ destination_detailed_zone=pl.when(
247
+ "8" + pl.col("destination_insee") == pl.col("destination_detailed_zone")
248
+ )
249
+ .then(None)
250
+ .when("9" + pl.col("destination_insee") == pl.col("destination_detailed_zone"))
251
+ .then(None)
252
+ .otherwise("destination_detailed_zone"),
253
+ )
254
+ return lf
nemobi/cerema/edgt.py ADDED
@@ -0,0 +1,254 @@
1
+ import io
2
+ import os
3
+ import re
4
+ from pathlib import Path
5
+ from zipfile import ZipFile
6
+
7
+ import geopandas as gpd
8
+
9
+ from nemobi.utils import MissingFileError, find_file, find_file_path
10
+
11
+ from .survey import CeremaStandardizer
12
+ from .zones import find_matching_column
13
+
14
+
15
+ class EDGTReader(CeremaStandardizer):
16
+ SURVEY_TYPE = "EDGT"
17
+
18
+ def households_filenames(self):
19
+ return get_files(self.source, "men")
20
+
21
+ def persons_filenames(self):
22
+ return get_files(self.source, "pers")
23
+
24
+ def trips_filenames(self):
25
+ return get_files(self.source, "depl")
26
+
27
+ def legs_filenames(self):
28
+ return get_files(self.source, "traj")
29
+
30
+ def special_locations_and_detailed_zones_filenames(self):
31
+ # This should match the Amiens 2010, Clermont-Ferrand 2012, and Lyon 2015 surveys.
32
+ faf_filename = find_file_path(self.source, ".*_faf_d.?coupagefin[.](tab|shp|mif)")
33
+ tel_filename = find_file_path(self.source, ".*_tel_d.?coupagefin[.](tab|shp|mif)")
34
+ if faf_filename and tel_filename:
35
+ # Amiens 2010 has two files.
36
+ return [faf_filename, tel_filename]
37
+ else:
38
+ return [find_file_path(self.source, ".*(_zf_gt|zinterne_gen_.*)[.](tab|shp|mif)")]
39
+
40
+ def special_locations_filenames(self):
41
+ faf_filename = find_file_path(self.source, ".*_faf_.*g.?n.?rateur.*[.](tab|shp|mif)")
42
+ tel_filename = find_file_path(self.source, ".*_tel_.*g.?n.?rateur.*[.](tab|shp|mif)")
43
+ if faf_filename and tel_filename:
44
+ # Saint-Quentin-en-Yvelines has two files, for phone and face-to-face surveys.
45
+ return [faf_filename, tel_filename]
46
+ else:
47
+ return [find_file_path(self.source, ".*(_gt_.*|_gt|g.?n.?rateur.*)[.](tab|shp|mif)")]
48
+
49
+ def detailed_zones_filenames(self):
50
+ faf_filename = find_file_path(self.source, ".*_faf_zones_fines[.](tab|shp|mif)")
51
+ tel_filename = find_file_path(self.source, ".*_tel_zones_fines[.](tab|shp|mif)")
52
+ if faf_filename and tel_filename:
53
+ # Nice 2009 and Saint-Quentin-en-Yvelines have two files, for phone and face-to-face
54
+ # surveys.
55
+ return [faf_filename, tel_filename]
56
+ else:
57
+ return [
58
+ find_file_path(
59
+ self.source, ".*(_zf|_zf_.*|zf08_.*|(?<!tel_)zones[_ ]fines)[.](tab|shp|mif)"
60
+ )
61
+ ]
62
+
63
+ def draw_zones_filenames(self):
64
+ return [find_file_path(self.source, ".*(_dtir|_secteurstirage)[.](tab|shp|mif)")]
65
+
66
+ def survey_name(self):
67
+ filename = find_file_path(self.source, ".*_std_faf_men.csv")
68
+ fn_match = re.match("(.*)_std_faf_men.csv", os.path.basename(filename))
69
+ if fn_match is not None:
70
+ return fn_match.group(1)
71
+ else:
72
+ return "unknown"
73
+
74
+ def gt_id_columns(self):
75
+ return [
76
+ "pôle_génér", # Thanks Saint-Quentin-en-Yvelines for this monstrosity.
77
+ "num_generateurs08",
78
+ "num_generateur08",
79
+ "num_gene2013",
80
+ "num_gene_2015",
81
+ "cod_pgt_2",
82
+ "zone_fine_gt",
83
+ "zf2015_nouveau_codage",
84
+ "code_gt",
85
+ "gt",
86
+ "zonefine",
87
+ "dfin",
88
+ "zf",
89
+ "num_zone_fine",
90
+ "num_zf",
91
+ "code",
92
+ ]
93
+
94
+ def zf_id_from_gt_columns(self):
95
+ return ["zf_rattachement", "rattacheme", "num_zf_2015", "zone_fine", "z_fine", "zf"]
96
+
97
+ def gt_name_columns(self):
98
+ return [
99
+ "pôles_gén", # Thanks again Saint-Quentin-en-Yvelines for this monstrosity.
100
+ "nom_generateur",
101
+ "nom_gt",
102
+ "nom_gene",
103
+ "nom_zone_fine",
104
+ "nom_zonefine",
105
+ "nom_zf",
106
+ "nom",
107
+ ]
108
+
109
+ def gt_type_columns(self):
110
+ return [
111
+ "typegd",
112
+ "nature_generateur",
113
+ "nom_type_gt",
114
+ "nom_type",
115
+ "catégorietxt",
116
+ "descriptif",
117
+ "nature",
118
+ "categorie",
119
+ "type_zonefine",
120
+ ]
121
+
122
+ def zf_id_columns(self):
123
+ return [
124
+ "num_zf_2013",
125
+ "num_zf_2015",
126
+ "zf2015_nouveau_codage",
127
+ "num_zf08",
128
+ "num_zf08_2",
129
+ "id_zf_cerema",
130
+ "zonefine",
131
+ "zone_fine",
132
+ "zf",
133
+ "dfin",
134
+ "num_zf",
135
+ "code",
136
+ ]
137
+
138
+ def zf_name_columns(self):
139
+ return ["zone_fin1", "nom_zonefine", "nom_zfine", "nom_zf", "nom"]
140
+
141
+ def dtir_id_columns(self):
142
+ return [
143
+ "bayonne_dtir", # Special case for Bayonne 2010 when reading the detailed zones.
144
+ "id_st",
145
+ "dtir_2016",
146
+ "dtir_s",
147
+ "num_dtir",
148
+ "num_tirage",
149
+ "num_secteur",
150
+ "num_secteurs",
151
+ "secteur",
152
+ "dtir",
153
+ "code",
154
+ ]
155
+
156
+ def dtir_name_columns(self):
157
+ return ["nom_dtir", "nom_dtir_enq", "nom_secteur"]
158
+
159
+ def insee_id_columns(self):
160
+ return [
161
+ "insee_commune",
162
+ "code_insee",
163
+ "codinsee",
164
+ "depcom",
165
+ "insee",
166
+ "id_commune",
167
+ "com_2",
168
+ "codcomm",
169
+ ]
170
+
171
+ def select_zf_column(self, gdf: gpd.GeoDataFrame):
172
+ # For Bayonne 2010 and Metz 2017, the ZF id can be computed by summing two columns.
173
+ pairs = (
174
+ ("bayonne_dtir", "CODE_ZF_VALIDE"), # Bayonne 2010.
175
+ ("Dtir", "Num_zfin"), # Metz 2017.
176
+ )
177
+ for sec_col, zf_num_col in pairs:
178
+ if sec_col in gdf.columns and zf_num_col in gdf.columns:
179
+ gdf["detailed_zone_id"] = gdf[sec_col].astype(str) + gdf[zf_num_col].astype(str)
180
+ break
181
+ # Normal case. Find the ZF id column by name.
182
+ super().select_zf_column(gdf)
183
+
184
+ def select_dtir_column(self, gdf: gpd.GeoDataFrame):
185
+ if "Z_fine" in gdf.columns and "NUM_DTIR" in gdf.columns:
186
+ # For Nantes 2015, there is 1 typo in NUM_DTIR so it is better to read the draw zone id
187
+ # from the first 3 characters of Z_fine instead.
188
+ gdf["draw_zone_id"] = gdf["Z_fine"].astype(str).str.slice(0, 3)
189
+ assert (gdf["draw_zone_id"].astype(int) != gdf["NUM_DTIR"].astype(int)).sum() <= 1
190
+ # This is the standard case.
191
+ super().select_dtir_column(gdf)
192
+ if "draw_zone_id" not in gdf.columns:
193
+ # For Nice 2009, Saint-Denis-de-la-Réunion 2016, and Saint-Quentin-en-Yvelines 2010,
194
+ # the draw_zone_id can be read from the first 3 characters of the GT column.
195
+ # For Angers 2012, it can be read from the first 3 characters of the ZF column.
196
+ for dtir_col in ("num_generateur08", "num_gene_2015", "pôle_génér", "code"):
197
+ if matching_col := find_matching_column(dtir_col, gdf):
198
+ gdf["draw_zone_id"] = gdf[matching_col].astype(str).str.slice(0, 3)
199
+
200
+ def select_zf_from_gt_column(self, gdf: gpd.GeoDataFrame):
201
+ # For Metz 2017, the ZF id can be computed by summing two columns.
202
+ if "Num_dtir" in gdf.columns and "Num_zfin" in gdf.columns:
203
+ gdf["detailed_zone_id"] = gdf["Num_dtir"].astype(str) + gdf["Num_zfin"].astype(str)
204
+ # Normal case. Find the ZF id column by name.
205
+ super().select_zf_from_gt_column(gdf)
206
+
207
+ def preprocess_special_locations(self, gdf: gpd.GeoDataFrame):
208
+ # Very very special case for Metz 2017, GT 003003 is actually 003301 (don't ask me why).
209
+ if "Code_gt" in gdf.columns and "Nom_gt" in gdf.columns:
210
+ match = gdf.loc[(gdf["Code_gt"] == "003003") & (gdf["Nom_gt"] == "Aldi")].index
211
+ if not match.empty:
212
+ assert len(match) == 1
213
+ gdf.loc[match, "Code_gt"] = "003301"
214
+ return gdf
215
+
216
+ def preprocess_detailed_zones(self, gdf: gpd.GeoDataFrame):
217
+ # For Bayonne 2010, column "CODE_ZONE_VALIDE" contains the draw zone id but there is a type:
218
+ # all values are "EMDxxx" where "xxx" is the draw zone id, except for one row where the
219
+ # value is "004007" while it should be "EMD004" (don't ask why).
220
+ if "CODE_ZONE_VALIDE" in gdf.columns:
221
+ gdf["bayonne_dtir"] = gdf["CODE_ZONE_VALIDE"].astype(str).str.slice(-3)
222
+ mask = gdf["CODE_ZONE_VALIDE"].astype(str).str.slice(0, 3) != "EMD"
223
+ assert mask.sum() <= 1
224
+ gdf.loc[mask, "bayonne_dtir"] = gdf["CODE_ZONE_VALIDE"].astype(str).str.slice(0, 3)
225
+ # For Montpellier 2014, the external zones are included in the ZF file. We remove them.
226
+ if "ID_ENQ" in gdf.columns:
227
+ gdf = gdf.loc[gdf["ID_ENQ"] == 1].copy()
228
+ if "ZONE_FINE" in gdf.columns and (gdf["ZONE_FINE"].str.len() == 7).all():
229
+ # For Saint-Quentin-en-Yvelines 2010, there is a leading zero that needs to be removed.
230
+ gdf["ZONE_FINE"] = gdf["ZONE_FINE"].str.slice(1)
231
+ return gdf
232
+
233
+ def postprocess_special_locations_and_detailed_zones(
234
+ self, zfs: gpd.GeoDataFrame | None, gts: gpd.GeoDataFrame | None
235
+ ):
236
+ if gts is None:
237
+ return zfs, gts
238
+ # Special case for Amiens 2010, the insee_id (from column CODE_INSEE) is not valid for GTs.
239
+ if "CODE_INSEE" in gts.columns and (gts["insee_id"].str.len() > 5).all():
240
+ gts.drop(columns=["insee_id"], inplace=True)
241
+ return zfs, gts
242
+
243
+
244
+ def get_files(source: Path | ZipFile, name: str) -> list[Path | io.BytesIO | MissingFileError]:
245
+ # In the EDGT surveys, there are two directories with "standardized" data in the Csv directory,
246
+ # usually "Fichiers_Standard_Face_a_face" and "Fichiers_Standard_Telephone" but it can be
247
+ # something else.
248
+ # Within these two directories, the CSV files to read are always
249
+ # "[SURVEY_NAME]_std_faf_[NAME].csv" and "[SURVEY_NAME]_std_tel_[NAME].csv" where NAME is either
250
+ # "men", "pers", "depl", or "traj".
251
+ return [
252
+ find_file(source, f".*_std_faf_{name}.csv"),
253
+ find_file(source, f".*_std_tel_{name}.csv"),
254
+ ]