geo-mapper-api 0.1.2__tar.gz → 0.3.1__tar.gz

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 (32) hide show
  1. geo_mapper_api-0.3.1/PKG-INFO +223 -0
  2. geo_mapper_api-0.3.1/README.md +206 -0
  3. geo_mapper_api-0.3.1/pyproject.toml +31 -0
  4. geo_mapper_api-0.3.1/src/geo_mapper_api/__init__.py +3 -0
  5. geo_mapper_api-0.3.1/src/geo_mapper_api/config.py +68 -0
  6. geo_mapper_api-0.3.1/src/geo_mapper_api/converters.py +111 -0
  7. geo_mapper_api-0.3.1/src/geo_mapper_api/evaluation.py +134 -0
  8. geo_mapper_api-0.3.1/src/geo_mapper_api/filters.py +19 -0
  9. geo_mapper_api-0.3.1/src/geo_mapper_api/inrix_to_osm.py +129 -0
  10. geo_mapper_api-0.3.1/src/geo_mapper_api/matching.py +337 -0
  11. geo_mapper_api-0.3.1/src/geo_mapper_api.egg-info/PKG-INFO +223 -0
  12. {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/SOURCES.txt +9 -1
  13. geo_mapper_api-0.3.1/src/geo_mapper_api.egg-info/requires.txt +8 -0
  14. geo_mapper_api-0.3.1/tests/test_config.py +101 -0
  15. geo_mapper_api-0.3.1/tests/test_converters.py +165 -0
  16. geo_mapper_api-0.3.1/tests/test_filters.py +38 -0
  17. geo_mapper_api-0.3.1/tests/test_inrix_to_osm.py +202 -0
  18. geo_mapper_api-0.3.1/tests/test_integration.py +130 -0
  19. geo_mapper_api-0.3.1/tests/test_matching.py +272 -0
  20. geo_mapper_api-0.1.2/PKG-INFO +0 -99
  21. geo_mapper_api-0.1.2/README.md +0 -82
  22. geo_mapper_api-0.1.2/pyproject.toml +0 -26
  23. geo_mapper_api-0.1.2/src/geo_mapper_api/__init__.py +0 -0
  24. geo_mapper_api-0.1.2/src/geo_mapper_api/converters.py +0 -299
  25. geo_mapper_api-0.1.2/src/geo_mapper_api/filters.py +0 -4
  26. geo_mapper_api-0.1.2/src/geo_mapper_api/inrix_to_osm.py +0 -102
  27. geo_mapper_api-0.1.2/src/geo_mapper_api.egg-info/PKG-INFO +0 -99
  28. geo_mapper_api-0.1.2/src/geo_mapper_api.egg-info/requires.txt +0 -9
  29. geo_mapper_api-0.1.2/tests/test_run.py +0 -12
  30. {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.1}/setup.cfg +0 -0
  31. {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/dependency_links.txt +0 -0
  32. {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/top_level.txt +0 -0
@@ -0,0 +1,223 @@
1
+ Metadata-Version: 2.4
2
+ Name: geo_mapper_api
3
+ Version: 0.3.1
4
+ Summary: A simple API for matching geospatial data to OSM IDs
5
+ Author-email: JP Talusan <jptalusan@gmail.com>
6
+ Project-URL: Homepage, https://github.com/scope-lab-vu/geospatial_mapper
7
+ Project-URL: Changelog, https://github.com/scope-lab-vu/geospatial_mapper/blob/main/CHANGELOG.md
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: osmnx<3,>=2.1.1
11
+ Requires-Dist: geopandas>=1.0.1
12
+ Requires-Dist: pandas>=2.1
13
+ Requires-Dist: shapely>=2.0
14
+ Requires-Dist: numpy>=1.26
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=8; extra == "dev"
17
+
18
+ # Quick start
19
+ Match INRIX XD segments to OpenStreetMap (OSM) road edges in four steps.
20
+
21
+ 1. **Install** (Python 3.11 or later):
22
+ ```
23
+ pip install geo_mapper_api
24
+ ```
25
+ 2. **Get two files** for your state from the INRIX [Data Download Service](https://docs.inrix.com/datadownload/datadownload/):
26
+ - the map release **GeoJSON** of XD segments, for example `USA_Tennessee.geojson`;
27
+ - the **OSM conflation CSV**, which lists the OSM ways under each XD, for example `USA_Tennessee.csv`.
28
+ 3. **Run it** for one or more counties:
29
+ ```python
30
+ from geo_mapper_api import inrix_to_osm
31
+
32
+ df = inrix_to_osm.serial("USA_Tennessee.geojson", "USA_Tennessee.csv", ["DAVIDSON"])
33
+ df.to_csv("davidson_inrix_osm.csv", index=False)
34
+ ```
35
+ The first run downloads the county's road network from OSM, which can take a few minutes.
36
+ 4. **Read the result**: one row per XD and OSM edge it runs along. `XDSegID` is the INRIX segment; `u`, `v` and `key` identify the OSM edge; `osmid` is one of its OSM ways and `highway` its road type. See [Usage](#usage) below for every column.
37
+
38
+ The sections below describe the input fields, the settings and how a match is decided.
39
+
40
+ # Examples
41
+ Matches on downtown Nashville. The light-blue band is an INRIX XD, its arrow showing the direction of travel; purple is the OSM edge the package matched to it. Grey lines are the other OSM roads nearby.
42
+
43
+ | | |
44
+ |---|---|
45
+ | ![A street crossing over an interstate: only the street is matched](docs/images/match_bridge_street.png) | ![The interstate under that street: only the interstate is matched](docs/images/match_bridge_interstate.png) |
46
+ | A street over an interstate is matched only to the street, not to the interstate lanes below. | The interstate under it is matched only to the interstate, not to the street crossing over. |
47
+ | ![A cloverleaf exit ramp matched along its whole curve](docs/images/match_cloverleaf_ramp.png) | ![A short XD on a roundabout matched to the roundabout edge in its direction](docs/images/match_roundabout.png) |
48
+ | A cloverleaf ramp is matched along its curve, not to the road it leaves. | A short XD on a roundabout is matched to the roundabout edge running its way. |
49
+
50
+ Each OSM edge runs between two intersections, so an edge can extend past the end of the XD it is matched to, as on the ramp above.
51
+
52
+ # Setup
53
+ This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
54
+ ```
55
+ pip install geo_mapper_api
56
+ ```
57
+
58
+ # Requirements
59
+ It needs both the `OSMConflation` and `GeoJSON` data for the target area. You can obtain both from Inrix [Data Download Service](https://docs.inrix.com/datadownload/datadownload/) provided you have an access token or login credentials.
60
+
61
+ This conflation `csv` should have the following features:
62
+ | Feature | Type | Example |
63
+ | ----------------------- | ------- | --------- |
64
+ | XDSegID | Integer | 136894283 |
65
+ | OSMWayIDs | String | 19659968;19659970 |
66
+ | OSMWayDirections | String | N;N |
67
+ | WayStartOffset\_m | Float | 1077.78 |
68
+ | WayEndOffset\_m | Float | 1851.31 |
69
+ | WayStartOffset\_percent | Float | 33.706 |
70
+ | WayEndOffset\_percent | Float | 57.897 |
71
+
72
+ Only `XDSegID`, `OSMWayIDs` and `OSMWayDirections` are required. `OSMWayIDs` and `OSMWayDirections` hold `;`-separated lists of the same length.
73
+
74
+ The `geojson` data needs `County`, `XDSegID`, `FRC` (INRIX road class, 1 to 5), `RoadName` and a line geometry in EPSG:4326, drawn in the direction of travel. INRIX files also carry fields such as these:
75
+ | Feature | Type | Example |
76
+ | ---------- | -------- | ------------------ |
77
+ | OID | Integer | 7931440 |
78
+ | XDSegID | Integer | 156418860 |
79
+ | PreviousXD | Float | nan |
80
+ | NextXDSegI | Float | 395960459.0 |
81
+ | FRC | Integer | 4 |
82
+ | RoadNumber | Float | nan |
83
+ | RoadName | String | DRHESSRD |
84
+ | LinearID | Float | nan |
85
+ | Country | String | UNITEDSTATES |
86
+ | State | String | TENNESSEE |
87
+ | County | String | HAYWOOD |
88
+ | District | Float | nan |
89
+ | PostalCode | String | 38006 |
90
+ | Miles | Float | 0.5902665205613952 |
91
+ | Lanes | Float | 1.0 |
92
+ | SlipRoad | Integer | 0 |
93
+ | SpecialRoa | Float | nan |
94
+ | RoadList | String | DRHESSRD |
95
+ | StartLat | Float | 35.67248 |
96
+ | StartLong | Float | -89.14147 |
97
+ | EndLat | Float | 35.666218484838986 |
98
+ | EndLong | Float | -89.13571015096953 |
99
+ | Bearing | String | S |
100
+ | XDGroup | Integer | 2013963 |
101
+ | ShapeSRID | Integer | 4326 |
102
+ | geometry | Geometry | LINESTRING |
103
+
104
+ # Usage
105
+ Give it the map release GeoJSON, the conflation CSV, and one or more county names. County names are matched case-insensitively.
106
+ ```python
107
+ import os
108
+
109
+ from geo_mapper_api import MatchConfig, inrix_to_osm
110
+
111
+ DATA_DIR = "./data"
112
+ geojson_path = os.path.join(DATA_DIR, "USA_Tennessee.geojson")
113
+ csv_path = os.path.join(DATA_DIR, "USA_Tennessee.csv")
114
+
115
+ if __name__ == "__main__":
116
+ df = inrix_to_osm.parallel(geojson_path, csv_path, ["WILLIAMSON", "DAVIDSON"], config=MatchConfig())
117
+ df.to_csv(os.path.join(DATA_DIR, "inrix_osm.csv"), index=False)
118
+ ```
119
+ `parallel` runs each county in its own process, using every CPU core but `reserved_cores` (2 by default). It must be called under `if __name__ == "__main__":`, because the worker processes import your script again. `serial` takes the same arguments, runs one county at a time, and needs no guard. `config` is optional; leaving it out uses the defaults below.
120
+
121
+ ## How a match is decided
122
+ The road network comes from OSM. It holds every way with a `highway` tag that is not drawn as an area, including service roads (driveways, parking aisles, alleys) and private roads. It leaves out footways, cycleways, paths, steps, pedestrian streets, bridleways, corridors, elevators, escalators, ladders, tracks, raceways, platforms, bus stops, trailheads, and roads that are under construction, proposed, planned, abandoned or razed.
123
+
124
+ For each XD, an OSM edge is matched when:
125
+ 1. it carries an OSM way that INRIX's conflation lists for the XD;
126
+ 2. it points the XD's direction of travel where they meet (INRIX's P/N flag is compared with this on two-way streets, and disagreements are logged as warnings);
127
+ 3. it runs along the XD: inside a band `band_half_width_m` either side of the XD, cut square at the XD's ends, the edge reaches at least `min_overlap_m` along the XD (half the XD's length for XDs shorter than twice that). Cross streets and the next block past the XD's end reach almost nowhere along it, so they are not matched.
128
+
129
+ An XD whose matches cover less than `fallback_below_coverage` of its length (usually because INRIX's way IDs are out of date) is searched again by geometry alone. Fallback matches are limited to general-traffic roads, which are `motorway`, `trunk`, `primary`, `secondary` and `tertiary` with their `_link` ramps, `unclassified`, `residential`, `living_street` and `road`. Service roads, busways and rest areas are matched only through INRIX's way IDs. Fallback matches must also pass a road-level rule: an interstate XD (`RoadName` starting `I-` and a digit) only matches `motorway` or `motorway_link` edges, and a non-interstate XD of road class 3 to 5 never matches a `motorway` edge. An XD with no `RoadName` is judged by its road class, so an unnamed interstate XD can lose motorway matches but never gains wrong ones.
130
+
131
+ ## Settings
132
+ Every tunable number lives in `MatchConfig`. Distances are in meters.
133
+
134
+ | Setting | Default | Meaning |
135
+ |---|---|---|
136
+ | `band_half_width_m` | 15.0 | half-width of the band around each XD |
137
+ | `min_overlap_m` | 10.0 | how far an edge must run along its XD inside the band |
138
+ | `fallback_below_coverage` | 0.9 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
139
+ | `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
140
+ | `reserved_cores` | 2 | CPU cores `parallel` leaves free |
141
+
142
+ Settings can come from a TOML file of top-level keys; keys left out keep their defaults:
143
+ ```toml
144
+ band_half_width_m = 20
145
+ min_overlap_m = 10
146
+ ```
147
+ ```python
148
+ config = MatchConfig.from_toml("matching.toml")
149
+ ```
150
+ A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
151
+
152
+ ## Known limits
153
+ - An XD drawn more than `band_half_width_m` from every OSM road stays unmatched or partly covered. This happens when the road was realigned, when OSM tags it as a track or a road under construction, which the road filter leaves out, or when it is a service road cut off from the rest of the network, which osmnx drops.
154
+ - An edge leaving the XD at an acute angle, such as a diverging ramp, can stay inside the band for 10 m or more and be matched. This mainly affects fallback matches, since a diverging road is usually a different OSM way.
155
+ - Limited-access parkways that OSM tags `motorway` but INRIX classes 3 to 5 cannot be recovered by the fallback; their way-ID matches are unaffected.
156
+
157
+ The result has one row per OSM edge and XD segment pair:
158
+ | Column | Type | Example |
159
+ |------------------|----------|-------------------------------------------|
160
+ | u | int | 202619796 |
161
+ | v | int | 202705554 |
162
+ | key | int | 0 |
163
+ | osmid | int | 19495638 |
164
+ | highway | str | primary |
165
+ | XDSegID | int | 1524404117 |
166
+ | osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
167
+ | inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
168
+ | overlap_m | float | 88.4 |
169
+ | source | str | conflation |
170
+ | county | str | DAVIDSON |
171
+
172
+ - `u`, `v` and `key` identify the edge in the osmnx graph.
173
+ - `osmid` is the OSM way that links the edge to the XD (the smallest, when several do). For `source == "geometry"` rows it is the smallest way ID on the edge.
174
+ - An osmnx edge can carry several OSM ways and `osmid` shows only one of them, so `osmid` is no join key. Join results to an osmnx graph or to other per-edge data on `u`, `v` and `key`.
175
+ - `highway` is the edge's OSM road type, such as `primary` or `service`. When osmnx merged ways of different types into one edge, it lists them sorted and joined with `;`, such as `residential;service`. It covers the whole edge, so it can name more types than the way in `osmid`, and it is never missing.
176
+ - `df[df["highway"] != "service"]` drops rows on edges that are only service roads. To keep only the general-traffic roads the fallback may match, filter with the package's own rule.
177
+ ```python
178
+ from geo_mapper_api.matching import fallback_type_allows
179
+
180
+ df = df[df["highway"].map(fallback_type_allows)]
181
+ ```
182
+ - Geometries are in EPSG:4326 (longitude, latitude).
183
+ - `overlap_m` is how far the edge runs along the XD, in meters.
184
+ - `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
185
+ - `county` holds the upper-cased county name.
186
+
187
+ # Errors
188
+ - `config` that isn't a `MatchConfig` raises `TypeError` before anything is read.
189
+ - Bad inputs raise `ValueError` before any county is processed. This covers a missing column, an unknown county, an empty county list, a missing or non-integer ID, an FRC outside 1 to 5, an empty or zero-length XD line, geometries not in EPSG:4326, and a conflation row whose way and direction lists differ in length. The message names the file, the column and the offending values.
190
+ - A failure while processing a county raises `RuntimeError` with a message like `county 'DAVIDSON' failed: ConnectionError: ...`.
191
+
192
+ # Logging
193
+ The package logs through Python's `logging` module and writes no files itself. To keep its logs:
194
+ ```python
195
+ import logging
196
+ import os
197
+
198
+ os.makedirs("log", exist_ok=True)
199
+ logging.basicConfig(filename="log/geo_mapper.log", level=logging.DEBUG)
200
+ ```
201
+
202
+ # Development
203
+ ```
204
+ python3.12 -m venv .venv
205
+ .venv/bin/pip install -e ".[dev]"
206
+ .venv/bin/pytest
207
+ ```
208
+ The unit tests run on small hand-made data and need no network.
209
+
210
+ The integration test runs on real INRIX data for downtown Nashville. The data is licensed, so it is never committed, and `tests/data/` is gitignored. Build it, then point the test at it:
211
+ ```
212
+ .venv/bin/python scripts/make_test_data.py --geojson-src HOST:/path/USA_Tennessee.geojson --csv-src HOST:/path/conflation.csv
213
+ GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
214
+ ```
215
+ The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
216
+
217
+ To compare this version's output with an earlier commit on the same data, run `scripts/compare_versions.py --base <commit> --base-python <a Python with that commit's dependencies>`. The base must be 0.3.0 or later. It prints a table per area and saves it under `log/`. Its download size and first-run time are only meaningful with an empty `osm_cache`, so give it a data folder of its own. `make_test_data.py` also writes all of Davidson County, which `--areas davidson` compares:
218
+ ```
219
+ .venv/bin/python scripts/compare_versions.py --base v0.3.0 --base-python .venv/bin/python --data <folder with davidson.geojson and davidson.csv> --areas davidson
220
+ ```
221
+
222
+ # Releasing
223
+ Set the new `version` in `pyproject.toml`, merge it to `main`, then push a matching tag such as `git tag v0.2.0 && git push origin v0.2.0`. The publish workflow checks that the tag matches the version and uploads to PyPI.
@@ -0,0 +1,206 @@
1
+ # Quick start
2
+ Match INRIX XD segments to OpenStreetMap (OSM) road edges in four steps.
3
+
4
+ 1. **Install** (Python 3.11 or later):
5
+ ```
6
+ pip install geo_mapper_api
7
+ ```
8
+ 2. **Get two files** for your state from the INRIX [Data Download Service](https://docs.inrix.com/datadownload/datadownload/):
9
+ - the map release **GeoJSON** of XD segments, for example `USA_Tennessee.geojson`;
10
+ - the **OSM conflation CSV**, which lists the OSM ways under each XD, for example `USA_Tennessee.csv`.
11
+ 3. **Run it** for one or more counties:
12
+ ```python
13
+ from geo_mapper_api import inrix_to_osm
14
+
15
+ df = inrix_to_osm.serial("USA_Tennessee.geojson", "USA_Tennessee.csv", ["DAVIDSON"])
16
+ df.to_csv("davidson_inrix_osm.csv", index=False)
17
+ ```
18
+ The first run downloads the county's road network from OSM, which can take a few minutes.
19
+ 4. **Read the result**: one row per XD and OSM edge it runs along. `XDSegID` is the INRIX segment; `u`, `v` and `key` identify the OSM edge; `osmid` is one of its OSM ways and `highway` its road type. See [Usage](#usage) below for every column.
20
+
21
+ The sections below describe the input fields, the settings and how a match is decided.
22
+
23
+ # Examples
24
+ Matches on downtown Nashville. The light-blue band is an INRIX XD, its arrow showing the direction of travel; purple is the OSM edge the package matched to it. Grey lines are the other OSM roads nearby.
25
+
26
+ | | |
27
+ |---|---|
28
+ | ![A street crossing over an interstate: only the street is matched](docs/images/match_bridge_street.png) | ![The interstate under that street: only the interstate is matched](docs/images/match_bridge_interstate.png) |
29
+ | A street over an interstate is matched only to the street, not to the interstate lanes below. | The interstate under it is matched only to the interstate, not to the street crossing over. |
30
+ | ![A cloverleaf exit ramp matched along its whole curve](docs/images/match_cloverleaf_ramp.png) | ![A short XD on a roundabout matched to the roundabout edge in its direction](docs/images/match_roundabout.png) |
31
+ | A cloverleaf ramp is matched along its curve, not to the road it leaves. | A short XD on a roundabout is matched to the roundabout edge running its way. |
32
+
33
+ Each OSM edge runs between two intersections, so an edge can extend past the end of the XD it is matched to, as on the ramp above.
34
+
35
+ # Setup
36
+ This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
37
+ ```
38
+ pip install geo_mapper_api
39
+ ```
40
+
41
+ # Requirements
42
+ It needs both the `OSMConflation` and `GeoJSON` data for the target area. You can obtain both from Inrix [Data Download Service](https://docs.inrix.com/datadownload/datadownload/) provided you have an access token or login credentials.
43
+
44
+ This conflation `csv` should have the following features:
45
+ | Feature | Type | Example |
46
+ | ----------------------- | ------- | --------- |
47
+ | XDSegID | Integer | 136894283 |
48
+ | OSMWayIDs | String | 19659968;19659970 |
49
+ | OSMWayDirections | String | N;N |
50
+ | WayStartOffset\_m | Float | 1077.78 |
51
+ | WayEndOffset\_m | Float | 1851.31 |
52
+ | WayStartOffset\_percent | Float | 33.706 |
53
+ | WayEndOffset\_percent | Float | 57.897 |
54
+
55
+ Only `XDSegID`, `OSMWayIDs` and `OSMWayDirections` are required. `OSMWayIDs` and `OSMWayDirections` hold `;`-separated lists of the same length.
56
+
57
+ The `geojson` data needs `County`, `XDSegID`, `FRC` (INRIX road class, 1 to 5), `RoadName` and a line geometry in EPSG:4326, drawn in the direction of travel. INRIX files also carry fields such as these:
58
+ | Feature | Type | Example |
59
+ | ---------- | -------- | ------------------ |
60
+ | OID | Integer | 7931440 |
61
+ | XDSegID | Integer | 156418860 |
62
+ | PreviousXD | Float | nan |
63
+ | NextXDSegI | Float | 395960459.0 |
64
+ | FRC | Integer | 4 |
65
+ | RoadNumber | Float | nan |
66
+ | RoadName | String | DRHESSRD |
67
+ | LinearID | Float | nan |
68
+ | Country | String | UNITEDSTATES |
69
+ | State | String | TENNESSEE |
70
+ | County | String | HAYWOOD |
71
+ | District | Float | nan |
72
+ | PostalCode | String | 38006 |
73
+ | Miles | Float | 0.5902665205613952 |
74
+ | Lanes | Float | 1.0 |
75
+ | SlipRoad | Integer | 0 |
76
+ | SpecialRoa | Float | nan |
77
+ | RoadList | String | DRHESSRD |
78
+ | StartLat | Float | 35.67248 |
79
+ | StartLong | Float | -89.14147 |
80
+ | EndLat | Float | 35.666218484838986 |
81
+ | EndLong | Float | -89.13571015096953 |
82
+ | Bearing | String | S |
83
+ | XDGroup | Integer | 2013963 |
84
+ | ShapeSRID | Integer | 4326 |
85
+ | geometry | Geometry | LINESTRING |
86
+
87
+ # Usage
88
+ Give it the map release GeoJSON, the conflation CSV, and one or more county names. County names are matched case-insensitively.
89
+ ```python
90
+ import os
91
+
92
+ from geo_mapper_api import MatchConfig, inrix_to_osm
93
+
94
+ DATA_DIR = "./data"
95
+ geojson_path = os.path.join(DATA_DIR, "USA_Tennessee.geojson")
96
+ csv_path = os.path.join(DATA_DIR, "USA_Tennessee.csv")
97
+
98
+ if __name__ == "__main__":
99
+ df = inrix_to_osm.parallel(geojson_path, csv_path, ["WILLIAMSON", "DAVIDSON"], config=MatchConfig())
100
+ df.to_csv(os.path.join(DATA_DIR, "inrix_osm.csv"), index=False)
101
+ ```
102
+ `parallel` runs each county in its own process, using every CPU core but `reserved_cores` (2 by default). It must be called under `if __name__ == "__main__":`, because the worker processes import your script again. `serial` takes the same arguments, runs one county at a time, and needs no guard. `config` is optional; leaving it out uses the defaults below.
103
+
104
+ ## How a match is decided
105
+ The road network comes from OSM. It holds every way with a `highway` tag that is not drawn as an area, including service roads (driveways, parking aisles, alleys) and private roads. It leaves out footways, cycleways, paths, steps, pedestrian streets, bridleways, corridors, elevators, escalators, ladders, tracks, raceways, platforms, bus stops, trailheads, and roads that are under construction, proposed, planned, abandoned or razed.
106
+
107
+ For each XD, an OSM edge is matched when:
108
+ 1. it carries an OSM way that INRIX's conflation lists for the XD;
109
+ 2. it points the XD's direction of travel where they meet (INRIX's P/N flag is compared with this on two-way streets, and disagreements are logged as warnings);
110
+ 3. it runs along the XD: inside a band `band_half_width_m` either side of the XD, cut square at the XD's ends, the edge reaches at least `min_overlap_m` along the XD (half the XD's length for XDs shorter than twice that). Cross streets and the next block past the XD's end reach almost nowhere along it, so they are not matched.
111
+
112
+ An XD whose matches cover less than `fallback_below_coverage` of its length (usually because INRIX's way IDs are out of date) is searched again by geometry alone. Fallback matches are limited to general-traffic roads, which are `motorway`, `trunk`, `primary`, `secondary` and `tertiary` with their `_link` ramps, `unclassified`, `residential`, `living_street` and `road`. Service roads, busways and rest areas are matched only through INRIX's way IDs. Fallback matches must also pass a road-level rule: an interstate XD (`RoadName` starting `I-` and a digit) only matches `motorway` or `motorway_link` edges, and a non-interstate XD of road class 3 to 5 never matches a `motorway` edge. An XD with no `RoadName` is judged by its road class, so an unnamed interstate XD can lose motorway matches but never gains wrong ones.
113
+
114
+ ## Settings
115
+ Every tunable number lives in `MatchConfig`. Distances are in meters.
116
+
117
+ | Setting | Default | Meaning |
118
+ |---|---|---|
119
+ | `band_half_width_m` | 15.0 | half-width of the band around each XD |
120
+ | `min_overlap_m` | 10.0 | how far an edge must run along its XD inside the band |
121
+ | `fallback_below_coverage` | 0.9 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
122
+ | `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
123
+ | `reserved_cores` | 2 | CPU cores `parallel` leaves free |
124
+
125
+ Settings can come from a TOML file of top-level keys; keys left out keep their defaults:
126
+ ```toml
127
+ band_half_width_m = 20
128
+ min_overlap_m = 10
129
+ ```
130
+ ```python
131
+ config = MatchConfig.from_toml("matching.toml")
132
+ ```
133
+ A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
134
+
135
+ ## Known limits
136
+ - An XD drawn more than `band_half_width_m` from every OSM road stays unmatched or partly covered. This happens when the road was realigned, when OSM tags it as a track or a road under construction, which the road filter leaves out, or when it is a service road cut off from the rest of the network, which osmnx drops.
137
+ - An edge leaving the XD at an acute angle, such as a diverging ramp, can stay inside the band for 10 m or more and be matched. This mainly affects fallback matches, since a diverging road is usually a different OSM way.
138
+ - Limited-access parkways that OSM tags `motorway` but INRIX classes 3 to 5 cannot be recovered by the fallback; their way-ID matches are unaffected.
139
+
140
+ The result has one row per OSM edge and XD segment pair:
141
+ | Column | Type | Example |
142
+ |------------------|----------|-------------------------------------------|
143
+ | u | int | 202619796 |
144
+ | v | int | 202705554 |
145
+ | key | int | 0 |
146
+ | osmid | int | 19495638 |
147
+ | highway | str | primary |
148
+ | XDSegID | int | 1524404117 |
149
+ | osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
150
+ | inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
151
+ | overlap_m | float | 88.4 |
152
+ | source | str | conflation |
153
+ | county | str | DAVIDSON |
154
+
155
+ - `u`, `v` and `key` identify the edge in the osmnx graph.
156
+ - `osmid` is the OSM way that links the edge to the XD (the smallest, when several do). For `source == "geometry"` rows it is the smallest way ID on the edge.
157
+ - An osmnx edge can carry several OSM ways and `osmid` shows only one of them, so `osmid` is no join key. Join results to an osmnx graph or to other per-edge data on `u`, `v` and `key`.
158
+ - `highway` is the edge's OSM road type, such as `primary` or `service`. When osmnx merged ways of different types into one edge, it lists them sorted and joined with `;`, such as `residential;service`. It covers the whole edge, so it can name more types than the way in `osmid`, and it is never missing.
159
+ - `df[df["highway"] != "service"]` drops rows on edges that are only service roads. To keep only the general-traffic roads the fallback may match, filter with the package's own rule.
160
+ ```python
161
+ from geo_mapper_api.matching import fallback_type_allows
162
+
163
+ df = df[df["highway"].map(fallback_type_allows)]
164
+ ```
165
+ - Geometries are in EPSG:4326 (longitude, latitude).
166
+ - `overlap_m` is how far the edge runs along the XD, in meters.
167
+ - `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
168
+ - `county` holds the upper-cased county name.
169
+
170
+ # Errors
171
+ - `config` that isn't a `MatchConfig` raises `TypeError` before anything is read.
172
+ - Bad inputs raise `ValueError` before any county is processed. This covers a missing column, an unknown county, an empty county list, a missing or non-integer ID, an FRC outside 1 to 5, an empty or zero-length XD line, geometries not in EPSG:4326, and a conflation row whose way and direction lists differ in length. The message names the file, the column and the offending values.
173
+ - A failure while processing a county raises `RuntimeError` with a message like `county 'DAVIDSON' failed: ConnectionError: ...`.
174
+
175
+ # Logging
176
+ The package logs through Python's `logging` module and writes no files itself. To keep its logs:
177
+ ```python
178
+ import logging
179
+ import os
180
+
181
+ os.makedirs("log", exist_ok=True)
182
+ logging.basicConfig(filename="log/geo_mapper.log", level=logging.DEBUG)
183
+ ```
184
+
185
+ # Development
186
+ ```
187
+ python3.12 -m venv .venv
188
+ .venv/bin/pip install -e ".[dev]"
189
+ .venv/bin/pytest
190
+ ```
191
+ The unit tests run on small hand-made data and need no network.
192
+
193
+ The integration test runs on real INRIX data for downtown Nashville. The data is licensed, so it is never committed, and `tests/data/` is gitignored. Build it, then point the test at it:
194
+ ```
195
+ .venv/bin/python scripts/make_test_data.py --geojson-src HOST:/path/USA_Tennessee.geojson --csv-src HOST:/path/conflation.csv
196
+ GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
197
+ ```
198
+ The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
199
+
200
+ To compare this version's output with an earlier commit on the same data, run `scripts/compare_versions.py --base <commit> --base-python <a Python with that commit's dependencies>`. The base must be 0.3.0 or later. It prints a table per area and saves it under `log/`. Its download size and first-run time are only meaningful with an empty `osm_cache`, so give it a data folder of its own. `make_test_data.py` also writes all of Davidson County, which `--areas davidson` compares:
201
+ ```
202
+ .venv/bin/python scripts/compare_versions.py --base v0.3.0 --base-python .venv/bin/python --data <folder with davidson.geojson and davidson.csv> --areas davidson
203
+ ```
204
+
205
+ # Releasing
206
+ Set the new `version` in `pyproject.toml`, merge it to `main`, then push a matching tag such as `git tag v0.2.0 && git push origin v0.2.0`. The publish workflow checks that the tag matches the version and uploads to PyPI.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "geo_mapper_api"
7
+ version = "0.3.1"
8
+ description = "A simple API for matching geospatial data to OSM IDs"
9
+ authors = [{ name="JP Talusan", email="jptalusan@gmail.com" }]
10
+ readme = "README.md"
11
+ requires-python = ">=3.11"
12
+ dependencies = ["osmnx>=2.1.1,<3",
13
+ "geopandas>=1.0.1",
14
+ "pandas>=2.1",
15
+ "shapely>=2.0",
16
+ "numpy>=1.26"]
17
+
18
+ [project.optional-dependencies]
19
+ dev = ["pytest>=8"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/scope-lab-vu/geospatial_mapper"
23
+ Changelog = "https://github.com/scope-lab-vu/geospatial_mapper/blob/main/CHANGELOG.md"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
27
+
28
+ [tool.pytest.ini_options]
29
+ testpaths = ["tests"]
30
+ log_file = "log/pytest.log"
31
+ log_file_level = "DEBUG"
@@ -0,0 +1,3 @@
1
+ from geo_mapper_api.config import MatchConfig
2
+
3
+ __all__ = ["MatchConfig"]
@@ -0,0 +1,68 @@
1
+ """Tunable settings for matching XD segments to OSM edges."""
2
+ import dataclasses
3
+ import math
4
+ import numbers
5
+ import tomllib
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclasses.dataclass(frozen=True)
10
+ class MatchConfig:
11
+ """Matching settings. Every distance is in meters.
12
+
13
+ band_half_width_m: half-width of the band drawn around each XD line, cut square at its ends.
14
+ min_overlap_m: how far an edge must run along its XD inside the band (half the XD's length
15
+ is enough for XDs shorter than twice this).
16
+ fallback_below_coverage: XDs whose way-ID matches cover less than this share of their length
17
+ are searched again by geometry. 0 turns the fallback off.
18
+ hull_buffer_m: margin added around a county's XDs for the OSM download.
19
+ reserved_cores: CPU cores parallel() leaves free.
20
+ """
21
+
22
+ band_half_width_m: float = 15.0
23
+ min_overlap_m: float = 10.0
24
+ fallback_below_coverage: float = 0.9
25
+ hull_buffer_m: float = 200.0
26
+ reserved_cores: int = 2
27
+
28
+ def __post_init__(self):
29
+ for name in ("band_half_width_m", "min_overlap_m", "fallback_below_coverage", "hull_buffer_m"):
30
+ value = getattr(self, name)
31
+ if isinstance(value, bool) or not isinstance(value, numbers.Real):
32
+ raise TypeError(f"MatchConfig.{name} must be a number, got {type(value).__name__} {value!r}")
33
+ try:
34
+ object.__setattr__(self, name, float(value))
35
+ except OverflowError:
36
+ raise ValueError(f"MatchConfig.{name} is too large: {value!r}") from None
37
+ if isinstance(self.reserved_cores, bool) or not isinstance(self.reserved_cores, numbers.Integral):
38
+ raise TypeError(f"MatchConfig.reserved_cores must be an integer, got "
39
+ f"{type(self.reserved_cores).__name__} {self.reserved_cores!r}")
40
+ object.__setattr__(self, "reserved_cores", int(self.reserved_cores))
41
+
42
+ checks = [
43
+ ("band_half_width_m", self.band_half_width_m > 0, "a finite number above 0"),
44
+ ("min_overlap_m", self.min_overlap_m > 0, "a finite number above 0"),
45
+ ("fallback_below_coverage", 0 <= self.fallback_below_coverage <= 1, "between 0 and 1"),
46
+ ("hull_buffer_m", self.hull_buffer_m >= 0, "a finite number of at least 0"),
47
+ ("reserved_cores", self.reserved_cores >= 0, "at least 0"),
48
+ ]
49
+ for name, ok, rule in checks:
50
+ value = getattr(self, name)
51
+ if not ok or (isinstance(value, float) and not math.isfinite(value)):
52
+ raise ValueError(f"MatchConfig.{name} must be {rule}, got {value!r}")
53
+
54
+ @classmethod
55
+ def from_toml(cls, path):
56
+ """Read settings from a TOML file of top-level keys; missing keys keep their defaults."""
57
+ try:
58
+ values = tomllib.loads(Path(path).read_text(encoding="utf-8"))
59
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
60
+ raise ValueError(f"{path}: cannot read TOML settings: {exc}") from exc
61
+ known = {field.name for field in dataclasses.fields(cls)}
62
+ unknown = sorted(set(values) - known)
63
+ if unknown:
64
+ raise ValueError(f"{path}: unknown settings {unknown}; known settings are {sorted(known)}")
65
+ try:
66
+ return cls(**values)
67
+ except (TypeError, ValueError) as exc:
68
+ raise ValueError(f"{path}: {exc}") from exc
@@ -0,0 +1,111 @@
1
+ import pandas as pd
2
+ import geopandas as gpd
3
+ import numpy as np
4
+ import osmnx as ox
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ INRIX_REQUIRED = ["County", "XDSegID", "FRC", "RoadName"]
10
+ CONFLATION_REQUIRED = ["XDSegID", "OSMWayIDs", "OSMWayDirections"]
11
+ FRC_VALUES = range(1, 6)
12
+
13
+
14
+ def normalize_counties(counties):
15
+ """Return county names stripped, upper-cased and de-duplicated, keeping first-seen order."""
16
+ names = [counties] if isinstance(counties, str) else list(counties)
17
+ if not names or not all(isinstance(n, str) and n.strip() for n in names):
18
+ raise ValueError(f"counties must be a non-empty list of county names, got {counties!r}")
19
+ return list(dict.fromkeys(n.strip().upper() for n in names))
20
+
21
+
22
+ def _require_columns(df, required, path):
23
+ missing = [c for c in required if c not in df.columns]
24
+ if missing:
25
+ raise ValueError(f"{path}: missing required columns {missing}")
26
+
27
+
28
+ def _to_int_ids(series, path, column):
29
+ """Parse IDs as int64, or raise naming the file, the column and up to five bad values."""
30
+ out = pd.to_numeric(series, errors="coerce")
31
+ bad = series[~np.isfinite(out) | (out != out.round())]
32
+ if not bad.empty:
33
+ raise ValueError(f"{path}: {column} has missing or non-integer values: {bad.head(5).tolist()}")
34
+ return out.astype("int64")
35
+
36
+
37
+ def load_and_prepare_inrix_data_for_multiple_counties(geojson_path, county_names):
38
+ """Load INRIX XD segments for the given counties.
39
+
40
+ county_names must already be normalised by normalize_counties.
41
+ """
42
+ inrix_df = gpd.read_file(geojson_path)
43
+ _require_columns(inrix_df, INRIX_REQUIRED, geojson_path)
44
+ if inrix_df.crs is None or inrix_df.crs.to_epsg() != 4326:
45
+ raise ValueError(f"{geojson_path}: geometries must be in EPSG:4326, got {inrix_df.crs}")
46
+ inrix_df.replace(to_replace='', value=np.nan, inplace=True)
47
+ filtered_df = inrix_df.loc[inrix_df["County"].isin(county_names)].copy()
48
+ missing = [c for c in county_names if c not in set(filtered_df["County"])]
49
+ if missing:
50
+ raise ValueError(f"counties not found in {geojson_path}: {missing}")
51
+ filtered_df["XDSegID"] = _to_int_ids(filtered_df["XDSegID"], geojson_path, "XDSegID")
52
+ filtered_df["FRC"] = _to_int_ids(filtered_df["FRC"], geojson_path, "FRC")
53
+ bad_frc = filtered_df.loc[~filtered_df["FRC"].isin(FRC_VALUES), "FRC"]
54
+ if not bad_frc.empty:
55
+ raise ValueError(f"{geojson_path}: FRC must be 1 to 5, got {bad_frc.head(5).tolist()}")
56
+ unusable = [not (g is not None and not g.is_empty and g.geom_type == "LineString" and g.length > 0)
57
+ for g in filtered_df.geometry]
58
+ if any(unusable):
59
+ ids = filtered_df.loc[unusable, "XDSegID"].head(5).tolist()
60
+ raise ValueError(f"{geojson_path}: XD geometries must be non-empty LineStrings, not for XDSegID {ids}")
61
+ logger.debug("loaded %d XD segments for %s from %s", len(filtered_df), county_names, geojson_path)
62
+ return filtered_df
63
+
64
+
65
+ def get_exterior_polygon(geodf, buffer_m):
66
+ """Return the convex hull of the geometries, grown by buffer_m meters, in EPSG:4326."""
67
+ utm = geodf.estimate_utm_crs()
68
+ hull = geodf.to_crs(utm).union_all().convex_hull.buffer(buffer_m)
69
+ return gpd.GeoSeries([hull], crs=utm).to_crs(4326).iloc[0]
70
+
71
+
72
+ def get_osm_graph(polygon, custom_filter):
73
+ """
74
+ Get OSM road network graph for the given polygon with the custom filter.
75
+
76
+ Parameters:
77
+ polygon (shapely.geometry.Polygon): The polygon defining the area of interest.
78
+ custom_filter (str): Custom filter to apply to the OSM data.
79
+
80
+ Returns:
81
+ networkx.MultiDiGraph: The road network graph for the given polygon.
82
+ """
83
+ G = ox.graph_from_polygon(polygon, custom_filter=custom_filter, network_type='drive')
84
+ return G
85
+
86
+ def load_conflation(csv_path, xd_ids):
87
+ """Load INRIX conflation rows for the given XDs, one row per (XD, OSM way)."""
88
+ conflation = pd.read_csv(csv_path, dtype={"OSMWayIDs": "string", "OSMWayDirections": "string"})
89
+ _require_columns(conflation, CONFLATION_REQUIRED, csv_path)
90
+ conflation["XDSegID"] = _to_int_ids(conflation["XDSegID"], csv_path, "XDSegID")
91
+ conflation = conflation.loc[conflation["XDSegID"].isin(xd_ids), CONFLATION_REQUIRED].copy()
92
+
93
+ no_ways = conflation["OSMWayIDs"].isna()
94
+ if no_ways.any():
95
+ logger.info("%s: dropped %d XDs with no OSM way IDs", csv_path, int(no_ways.sum()))
96
+ conflation = conflation.loc[~no_ways].copy()
97
+
98
+ conflation["OSMWayIDs"] = conflation["OSMWayIDs"].str.split(";")
99
+ conflation["OSMWayDirections"] = conflation["OSMWayDirections"].str.split(";")
100
+ # A missing direction gives <NA> lengths, which count as a mismatch.
101
+ id_counts = conflation["OSMWayIDs"].str.len().astype("Int64")
102
+ direction_counts = conflation["OSMWayDirections"].str.len().astype("Int64")
103
+ mismatch = id_counts.ne(direction_counts).fillna(True).astype(bool)
104
+ if mismatch.any():
105
+ ids = conflation.loc[mismatch, "XDSegID"].head(5).tolist()
106
+ raise ValueError(f"{csv_path}: OSMWayIDs and OSMWayDirections differ in length for XDSegID {ids}")
107
+
108
+ conflation = conflation.explode(["OSMWayIDs", "OSMWayDirections"])
109
+ conflation["OSMWayIDs"] = _to_int_ids(conflation["OSMWayIDs"], csv_path, "OSMWayIDs")
110
+ logger.debug("loaded %d conflation rows from %s", len(conflation), csv_path)
111
+ return conflation.reset_index(drop=True)