geo-mapper-api 0.3.0__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 (23) hide show
  1. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/PKG-INFO +32 -6
  2. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/README.md +31 -5
  3. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/pyproject.toml +1 -1
  4. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api/config.py +1 -1
  5. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api/evaluation.py +23 -10
  6. geo_mapper_api-0.3.1/src/geo_mapper_api/filters.py +19 -0
  7. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api/inrix_to_osm.py +3 -1
  8. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api/matching.py +43 -7
  9. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/PKG-INFO +32 -6
  10. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/SOURCES.txt +1 -0
  11. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/tests/test_config.py +1 -1
  12. geo_mapper_api-0.3.1/tests/test_filters.py +38 -0
  13. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/tests/test_inrix_to_osm.py +33 -0
  14. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/tests/test_integration.py +15 -3
  15. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/tests/test_matching.py +41 -0
  16. geo_mapper_api-0.3.0/src/geo_mapper_api/filters.py +0 -4
  17. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/setup.cfg +0 -0
  18. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api/__init__.py +0 -0
  19. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api/converters.py +0 -0
  20. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/dependency_links.txt +0 -0
  21. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/requires.txt +0 -0
  22. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/src/geo_mapper_api.egg-info/top_level.txt +0 -0
  23. {geo_mapper_api-0.3.0 → geo_mapper_api-0.3.1}/tests/test_converters.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: geo_mapper_api
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: A simple API for matching geospatial data to OSM IDs
5
5
  Author-email: JP Talusan <jptalusan@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/scope-lab-vu/geospatial_mapper
@@ -33,10 +33,22 @@ Match INRIX XD segments to OpenStreetMap (OSM) road edges in four steps.
33
33
  df.to_csv("davidson_inrix_osm.csv", index=False)
34
34
  ```
35
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 the OSM way. See [Usage](#usage) below for every column.
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
37
 
38
38
  The sections below describe the input fields, the settings and how a match is decided.
39
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
+
40
52
  # Setup
41
53
  This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
42
54
  ```
@@ -107,12 +119,14 @@ if __name__ == "__main__":
107
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.
108
120
 
109
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
+
110
124
  For each XD, an OSM edge is matched when:
111
125
  1. it carries an OSM way that INRIX's conflation lists for the XD;
112
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);
113
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.
114
128
 
115
- 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 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.
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.
116
130
 
117
131
  ## Settings
118
132
  Every tunable number lives in `MatchConfig`. Distances are in meters.
@@ -121,7 +135,7 @@ Every tunable number lives in `MatchConfig`. Distances are in meters.
121
135
  |---|---|---|
122
136
  | `band_half_width_m` | 15.0 | half-width of the band around each XD |
123
137
  | `min_overlap_m` | 10.0 | how far an edge must run along its XD inside the band |
124
- | `fallback_below_coverage` | 0.5 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
138
+ | `fallback_below_coverage` | 0.9 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
125
139
  | `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
126
140
  | `reserved_cores` | 2 | CPU cores `parallel` leaves free |
127
141
 
@@ -136,7 +150,7 @@ config = MatchConfig.from_toml("matching.toml")
136
150
  A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
137
151
 
138
152
  ## Known limits
139
- - An XD drawn more than `band_half_width_m` from every OSM road (the road was realigned, or OSM tags it as a track or service road the road filter leaves out) stays unmatched or partly covered.
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.
140
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.
141
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.
142
156
 
@@ -147,6 +161,7 @@ The result has one row per OSM edge and XD segment pair:
147
161
  | v | int | 202705554 |
148
162
  | key | int | 0 |
149
163
  | osmid | int | 19495638 |
164
+ | highway | str | primary |
150
165
  | XDSegID | int | 1524404117 |
151
166
  | osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
152
167
  | inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
@@ -156,6 +171,14 @@ The result has one row per OSM edge and XD segment pair:
156
171
 
157
172
  - `u`, `v` and `key` identify the edge in the osmnx graph.
158
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
+ ```
159
182
  - Geometries are in EPSG:4326 (longitude, latitude).
160
183
  - `overlap_m` is how far the edge runs along the XD, in meters.
161
184
  - `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
@@ -191,7 +214,10 @@ GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
191
214
  ```
192
215
  The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
193
216
 
194
- 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>`. It prints a table per area and saves it under `log/`.
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
+ ```
195
221
 
196
222
  # Releasing
197
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.
@@ -16,10 +16,22 @@ Match INRIX XD segments to OpenStreetMap (OSM) road edges in four steps.
16
16
  df.to_csv("davidson_inrix_osm.csv", index=False)
17
17
  ```
18
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 the OSM way. See [Usage](#usage) below for every column.
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
20
 
21
21
  The sections below describe the input fields, the settings and how a match is decided.
22
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
+
23
35
  # Setup
24
36
  This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
25
37
  ```
@@ -90,12 +102,14 @@ if __name__ == "__main__":
90
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.
91
103
 
92
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
+
93
107
  For each XD, an OSM edge is matched when:
94
108
  1. it carries an OSM way that INRIX's conflation lists for the XD;
95
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);
96
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.
97
111
 
98
- 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 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.
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.
99
113
 
100
114
  ## Settings
101
115
  Every tunable number lives in `MatchConfig`. Distances are in meters.
@@ -104,7 +118,7 @@ Every tunable number lives in `MatchConfig`. Distances are in meters.
104
118
  |---|---|---|
105
119
  | `band_half_width_m` | 15.0 | half-width of the band around each XD |
106
120
  | `min_overlap_m` | 10.0 | how far an edge must run along its XD inside the band |
107
- | `fallback_below_coverage` | 0.5 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
121
+ | `fallback_below_coverage` | 0.9 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
108
122
  | `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
109
123
  | `reserved_cores` | 2 | CPU cores `parallel` leaves free |
110
124
 
@@ -119,7 +133,7 @@ config = MatchConfig.from_toml("matching.toml")
119
133
  A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
120
134
 
121
135
  ## Known limits
122
- - An XD drawn more than `band_half_width_m` from every OSM road (the road was realigned, or OSM tags it as a track or service road the road filter leaves out) stays unmatched or partly covered.
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.
123
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.
124
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.
125
139
 
@@ -130,6 +144,7 @@ The result has one row per OSM edge and XD segment pair:
130
144
  | v | int | 202705554 |
131
145
  | key | int | 0 |
132
146
  | osmid | int | 19495638 |
147
+ | highway | str | primary |
133
148
  | XDSegID | int | 1524404117 |
134
149
  | osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
135
150
  | inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
@@ -139,6 +154,14 @@ The result has one row per OSM edge and XD segment pair:
139
154
 
140
155
  - `u`, `v` and `key` identify the edge in the osmnx graph.
141
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
+ ```
142
165
  - Geometries are in EPSG:4326 (longitude, latitude).
143
166
  - `overlap_m` is how far the edge runs along the XD, in meters.
144
167
  - `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
@@ -174,7 +197,10 @@ GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
174
197
  ```
175
198
  The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
176
199
 
177
- 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>`. It prints a table per area and saves it under `log/`.
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
+ ```
178
204
 
179
205
  # Releasing
180
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.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "geo_mapper_api"
7
- version = "0.3.0"
7
+ version = "0.3.1"
8
8
  description = "A simple API for matching geospatial data to OSM IDs"
9
9
  authors = [{ name="JP Talusan", email="jptalusan@gmail.com" }]
10
10
  readme = "README.md"
@@ -21,7 +21,7 @@ class MatchConfig:
21
21
 
22
22
  band_half_width_m: float = 15.0
23
23
  min_overlap_m: float = 10.0
24
- fallback_below_coverage: float = 0.5
24
+ fallback_below_coverage: float = 0.9
25
25
  hull_buffer_m: float = 200.0
26
26
  reserved_cores: int = 2
27
27
 
@@ -7,6 +7,7 @@ scored the same way.
7
7
  import geopandas as gpd
8
8
  import osmnx as ox
9
9
  import pandas as pd
10
+ import shapely
10
11
 
11
12
  import geo_mapper_api.converters as gma
12
13
  from geo_mapper_api import filters, matching
@@ -67,19 +68,29 @@ def area_edges(xds, config):
67
68
 
68
69
 
69
70
  def road_nearby(xds, edges, config):
70
- """XDSegIDs with an OSM road within band_half_width_m along at least ROAD_NEARBY_SHARE of their length."""
71
+ """XDSegIDs with an OSM road within band_half_width_m along at least ROAD_NEARBY_SHARE of their length.
72
+
73
+ Each XD is measured against only the edges within band_half_width_m of it, found with a spatial
74
+ index. Farther edges cannot reach the line, so this equals buffering the whole network, and it
75
+ stays fast for a whole county.
76
+ """
71
77
  utm = xds.estimate_utm_crs()
72
- reach = edges.to_crs(utm).union_all().buffer(config.band_half_width_m)
73
- lines = xds.to_crs(utm).geometry
74
- return {xd for xd, line in zip(xds["XDSegID"], lines)
75
- if line.intersection(reach).length >= ROAD_NEARBY_SHARE * line.length}
78
+ edge_lines = edges.to_crs(utm).geometry.to_numpy()
79
+ tree = shapely.STRtree(edge_lines)
80
+ nearby = set()
81
+ for xd, line in zip(xds["XDSegID"], xds.to_crs(utm).geometry):
82
+ near = edge_lines[tree.query(line, predicate="dwithin", distance=config.band_half_width_m)]
83
+ reach = shapely.union_all(near).buffer(config.band_half_width_m)
84
+ if line.intersection(reach).length >= ROAD_NEARBY_SHARE * line.length:
85
+ nearby.add(xd)
86
+ return nearby
76
87
 
77
88
 
78
89
  def wrong_level(result, xds, crossings, highway):
79
90
  """(wrong, unresolved): crossing XDs' rows on an edge the road-level rule refuses.
80
91
 
81
- Rows whose edge isn't in `highway` (possible for another version's output, if osmnx numbered
82
- edges differently) are counted as unresolved, never as fine.
92
+ highway: the road types of the graph the result was matched against, indexed by (u, v, key).
93
+ Rows whose edge isn't in it are counted as unresolved, never as fine.
83
94
  """
84
95
  crossing_xds = set(crossings["interstate"]) | set(crossings["other"])
85
96
  info = xds.set_index("XDSegID")
@@ -94,10 +105,12 @@ def wrong_level(result, xds, crossings, highway):
94
105
  return wrong, unresolved
95
106
 
96
107
 
97
- def summary(result, xds, edges, config):
108
+ def summary(result, xds, edges, config, highway=None):
98
109
  """The measures used to judge and compare matching results, as a dict.
99
110
 
100
- edges: the area's OSM edges from area_edges, shared by every version being compared.
111
+ edges: the area's OSM road edges from area_edges, which decide which XDs have a road nearby.
112
+ highway: the road types of the graph the result was matched against, for the wrong-level check.
113
+ It defaults to edges["highway"]. A version with another filter passes its own graph's here.
101
114
  """
102
115
  table = along_table(result, xds, config)
103
116
  coverage = xd_coverage_table(table, xds)
@@ -105,7 +118,7 @@ def summary(result, xds, edges, config):
105
118
  nearby = road_nearby(xds, edges, config)
106
119
  judged = coverage[coverage["XDSegID"].isin(matched & nearby)]["coverage"]
107
120
  crossings = interstate_crossings(xds)
108
- wrong, unresolved = wrong_level(result, xds, crossings, edges["highway"])
121
+ wrong, unresolved = wrong_level(result, xds, crossings, edges["highway"] if highway is None else highway)
109
122
  return {
110
123
  "edge-XD pairs": len(result.drop_duplicates(PAIR)),
111
124
  "matched XDs": len(matched),
@@ -0,0 +1,19 @@
1
+ """The Overpass filter for the OSM road network each county is matched against.
2
+
3
+ osmnx uses a custom filter in place of its network_type presets, so this string is the whole
4
+ filter. It keeps every way with a highway tag, including service roads and private roads, which
5
+ INRIX's conflation lists, and leaves out roads drawn as areas and the values below.
6
+ Overpass's `!~` also matches ways without the key, so `["highway"]` must be required on its own.
7
+ The exclusion pattern is anchored, so it removes only the exact values listed.
8
+ """
9
+ EXCLUDED_HIGHWAY = (
10
+ # Ways for people on foot, bike or horse.
11
+ "footway", "cycleway", "path", "steps", "pedestrian", "bridleway", "corridor", "elevator",
12
+ "escalator", "ladder",
13
+ # Not open roads.
14
+ "track", "construction", "proposed", "planned", "abandoned", "razed", "no", "raceway",
15
+ # Not carriageways.
16
+ "platform", "bus_stop", "trailhead",
17
+ )
18
+
19
+ base_filter = '["highway"]["area"!~"yes"]["highway"!~"^(' + "|".join(EXCLUDED_HIGHWAY) + ')$"]'
@@ -12,7 +12,7 @@ from geo_mapper_api.config import MatchConfig
12
12
 
13
13
  logger = logging.getLogger(__name__)
14
14
 
15
- RESULT_COLUMNS = ["u", "v", "key", "osmid", "XDSegID", "osm_geom", "inrix_geom",
15
+ RESULT_COLUMNS = ["u", "v", "key", "osmid", "highway", "XDSegID", "osm_geom", "inrix_geom",
16
16
  "overlap_m", "source", "county"]
17
17
 
18
18
 
@@ -90,6 +90,8 @@ def serial(geojson_path, csv_path, counties, config=None):
90
90
  A DataFrame with RESULT_COLUMNS, one row per (u, v, key, XDSegID). Geometries are in
91
91
  EPSG:4326. overlap_m is how far the edge runs along the XD, in meters. source is
92
92
  "conflation" for matches through INRIX's way IDs and "geometry" for the fallback.
93
+ highway is the edge's OSM road types, sorted and joined with ";". osmid is one of the
94
+ edge's ways, so join on u, v and key.
93
95
 
94
96
  Raises:
95
97
  TypeError: config is not a MatchConfig.
@@ -10,6 +10,8 @@ zone). An edge belongs to an XD when it runs along the XD, in the XD's direction
10
10
  INRIX's P/N flag is compared with it on two-way edges and disagreements are logged.
11
11
  - XDs left mostly uncovered (out-of-date way IDs) are searched again by geometry alone, with a
12
12
  road-level rule so an XD can't match a road on another level.
13
+ - The fallback only matches general-traffic road types. Service roads, busways and the like are
14
+ matched only through INRIX's way IDs.
13
15
  """
14
16
  import logging
15
17
  import re
@@ -26,6 +28,12 @@ logger = logging.getLogger(__name__)
26
28
  INTERSTATE_NAME = re.compile(r"^I-\d")
27
29
  MOTORWAY = "motorway"
28
30
  INTERSTATE_EDGES = {"motorway", "motorway_link"}
31
+ # Road types the geometric fallback may match. residential_link is non-standard but occurs in OSM.
32
+ FALLBACK_HIGHWAY = frozenset({
33
+ "motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link",
34
+ "secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified",
35
+ "residential", "residential_link", "living_street", "road",
36
+ })
29
37
 
30
38
  # Geometry constants (not settings): how a seam crossing is told apart from an ordinary segment,
31
39
  # the step used to read a line's local direction, and the rounding tolerance of the keep test.
@@ -35,9 +43,11 @@ TANGENT_STEP_M = 1.0
35
43
  TOLERANCE_M = 1e-6
36
44
 
37
45
  PAIR = ["u", "v", "key", "XDSegID"]
38
- MATCH_COLUMNS = ["u", "v", "key", "osmid", "XDSegID", "osm_geom", "inrix_geom", "overlap_m", "source"]
39
- MATCH_TYPES = {"u": "int64", "v": "int64", "key": "int64", "osmid": "int64", "XDSegID": "int64", "overlap_m": "float64"}
40
- _ROW_COLUMNS = ["u", "v", "key", "osmid", "XDSegID", "overlap_m", "intervals"]
46
+ MATCH_COLUMNS = ["u", "v", "key", "osmid", "highway", "XDSegID", "osm_geom", "inrix_geom", "overlap_m", "source"]
47
+ # highway is pinned to object so pandas 3 doesn't infer its own str dtype and empty and full results agree.
48
+ MATCH_TYPES = {"u": "int64", "v": "int64", "key": "int64", "osmid": "int64", "highway": "object",
49
+ "XDSegID": "int64", "overlap_m": "float64"}
50
+ _ROW_COLUMNS = ["u", "v", "key", "osmid", "highway", "XDSegID", "overlap_m", "intervals"]
41
51
 
42
52
 
43
53
  def band(xd_line, half_width_m):
@@ -113,8 +123,29 @@ def required_overlap_m(xd_length_m, min_overlap_m):
113
123
  return min(min_overlap_m, xd_length_m / 2)
114
124
 
115
125
 
116
- def _tags(highway):
117
- return set(highway) if isinstance(highway, list) else {highway}
126
+ def road_types(highway):
127
+ """The set of road types in an edge's highway value, which is a list, a ";"-joined string, or missing."""
128
+ if isinstance(highway, list):
129
+ return set(highway)
130
+ if isinstance(highway, str):
131
+ return {t for t in highway.split(";") if t}
132
+ return set()
133
+
134
+
135
+ def fallback_type_allows(highway):
136
+ """Whether the geometric fallback may match an edge with these OSM highway tags."""
137
+ return bool(road_types(highway) & FALLBACK_HIGHWAY)
138
+
139
+
140
+ def highway_label(highway):
141
+ """An edge's road types as sorted ";"-joined text, such as "residential;service".
142
+
143
+ The road filter requires a highway tag, so an edge without one means the graph came from elsewhere.
144
+ """
145
+ types = road_types(highway)
146
+ if not types:
147
+ raise ValueError(f"edge has no OSM highway tag (highway={highway!r})")
148
+ return ";".join(sorted(types))
118
149
 
119
150
 
120
151
  def is_interstate(road_name):
@@ -124,7 +155,7 @@ def is_interstate(road_name):
124
155
 
125
156
  def road_level_allows(road_name, frc, highway):
126
157
  """Whether a fallback match may put this XD on an edge with these OSM highway tags."""
127
- tags = _tags(highway)
158
+ tags = road_types(highway)
128
159
  if is_interstate(road_name):
129
160
  return bool(tags & INTERSTATE_EDGES)
130
161
  if frc <= 2:
@@ -222,6 +253,8 @@ def geometry_fallback(edges_utm, xds_utm, seen_pairs, config):
222
253
  reasons.append("overlap")
223
254
  elif not runs_with:
224
255
  reasons.append("direction")
256
+ elif not fallback_type_allows(highway):
257
+ reasons.append("road_type")
225
258
  elif not road_level_allows(road_name, frc, highway):
226
259
  reasons.append("road_level")
227
260
  else:
@@ -230,6 +263,7 @@ def geometry_fallback(edges_utm, xds_utm, seen_pairs, config):
230
263
  kept = rows[[r is None for r in reasons]]
231
264
  out = pd.DataFrame({"u": kept["u"].to_numpy(), "v": kept["v"].to_numpy(), "key": kept["key"].to_numpy(),
232
265
  "osmid": [_smallest_way(o) for o in kept["osmid"]],
266
+ "highway": kept["highway"].to_numpy(),
233
267
  "XDSegID": kept["XDSegID"].to_numpy(), "overlap_m": kept["along_m"].to_numpy(),
234
268
  "intervals": kept["intervals"].to_list()})
235
269
  return _rows(out), rejected
@@ -266,7 +300,8 @@ def match_county(edges, conflation, xds, config):
266
300
  kept = measured[long_enough & measured["runs_with"]]
267
301
  conflation_rows = _rows(pd.DataFrame({
268
302
  "u": kept["u"].to_numpy(), "v": kept["v"].to_numpy(), "key": kept["key"].to_numpy(),
269
- "osmid": kept["osmid"].to_numpy(), "XDSegID": kept["XDSegID"].to_numpy(),
303
+ "osmid": kept["osmid"].to_numpy(), "highway": kept["highway"].to_numpy(),
304
+ "XDSegID": kept["XDSegID"].to_numpy(),
270
305
  "overlap_m": kept["along_m"].to_numpy(), "intervals": kept["intervals"].to_list()}))
271
306
  logger.debug("%d way-ID rows kept by direction and the runs-along rule", len(conflation_rows))
272
307
 
@@ -286,6 +321,7 @@ def match_county(edges, conflation, xds, config):
286
321
  rows["source_rank"] = (rows["source"] != "conflation").astype(int)
287
322
  rows = (rows.sort_values(["source_rank", "osmid"], kind="stable")
288
323
  .drop_duplicates(PAIR).drop(columns=["source_rank", "intervals"]))
324
+ rows["highway"] = [highway_label(h) for h in rows["highway"]]
289
325
 
290
326
  osm_geom = dict(zip(map(tuple, edges_4326[["u", "v", "key"]].itertuples(index=False)), edges_4326.geometry))
291
327
  xd_geom = dict(zip(xds["XDSegID"], xds.geometry))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: geo_mapper_api
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: A simple API for matching geospatial data to OSM IDs
5
5
  Author-email: JP Talusan <jptalusan@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/scope-lab-vu/geospatial_mapper
@@ -33,10 +33,22 @@ Match INRIX XD segments to OpenStreetMap (OSM) road edges in four steps.
33
33
  df.to_csv("davidson_inrix_osm.csv", index=False)
34
34
  ```
35
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 the OSM way. See [Usage](#usage) below for every column.
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
37
 
38
38
  The sections below describe the input fields, the settings and how a match is decided.
39
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
+
40
52
  # Setup
41
53
  This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
42
54
  ```
@@ -107,12 +119,14 @@ if __name__ == "__main__":
107
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.
108
120
 
109
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
+
110
124
  For each XD, an OSM edge is matched when:
111
125
  1. it carries an OSM way that INRIX's conflation lists for the XD;
112
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);
113
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.
114
128
 
115
- 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 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.
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.
116
130
 
117
131
  ## Settings
118
132
  Every tunable number lives in `MatchConfig`. Distances are in meters.
@@ -121,7 +135,7 @@ Every tunable number lives in `MatchConfig`. Distances are in meters.
121
135
  |---|---|---|
122
136
  | `band_half_width_m` | 15.0 | half-width of the band around each XD |
123
137
  | `min_overlap_m` | 10.0 | how far an edge must run along its XD inside the band |
124
- | `fallback_below_coverage` | 0.5 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
138
+ | `fallback_below_coverage` | 0.9 | XDs covered less than this share are searched by geometry; 0 turns the fallback off |
125
139
  | `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
126
140
  | `reserved_cores` | 2 | CPU cores `parallel` leaves free |
127
141
 
@@ -136,7 +150,7 @@ config = MatchConfig.from_toml("matching.toml")
136
150
  A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
137
151
 
138
152
  ## Known limits
139
- - An XD drawn more than `band_half_width_m` from every OSM road (the road was realigned, or OSM tags it as a track or service road the road filter leaves out) stays unmatched or partly covered.
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.
140
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.
141
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.
142
156
 
@@ -147,6 +161,7 @@ The result has one row per OSM edge and XD segment pair:
147
161
  | v | int | 202705554 |
148
162
  | key | int | 0 |
149
163
  | osmid | int | 19495638 |
164
+ | highway | str | primary |
150
165
  | XDSegID | int | 1524404117 |
151
166
  | osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
152
167
  | inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
@@ -156,6 +171,14 @@ The result has one row per OSM edge and XD segment pair:
156
171
 
157
172
  - `u`, `v` and `key` identify the edge in the osmnx graph.
158
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
+ ```
159
182
  - Geometries are in EPSG:4326 (longitude, latitude).
160
183
  - `overlap_m` is how far the edge runs along the XD, in meters.
161
184
  - `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
@@ -191,7 +214,10 @@ GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
191
214
  ```
192
215
  The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
193
216
 
194
- 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>`. It prints a table per area and saves it under `log/`.
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
+ ```
195
221
 
196
222
  # Releasing
197
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.
@@ -14,6 +14,7 @@ src/geo_mapper_api.egg-info/requires.txt
14
14
  src/geo_mapper_api.egg-info/top_level.txt
15
15
  tests/test_config.py
16
16
  tests/test_converters.py
17
+ tests/test_filters.py
17
18
  tests/test_inrix_to_osm.py
18
19
  tests/test_integration.py
19
20
  tests/test_matching.py
@@ -15,7 +15,7 @@ def MatchConfig():
15
15
  def test_defaults(MatchConfig):
16
16
  config = MatchConfig()
17
17
  assert (config.band_half_width_m, config.min_overlap_m, config.fallback_below_coverage,
18
- config.hull_buffer_m, config.reserved_cores) == (15.0, 10.0, 0.5, 200.0, 2)
18
+ config.hull_buffer_m, config.reserved_cores) == (15.0, 10.0, 0.9, 200.0, 2)
19
19
 
20
20
 
21
21
  def test_exported_from_the_package(MatchConfig):
@@ -0,0 +1,38 @@
1
+ """The OSM download filter, read as Overpass reads it (no network)."""
2
+ import re
3
+
4
+ import pytest
5
+
6
+ from geo_mapper_api.filters import EXCLUDED_HIGHWAY, base_filter
7
+
8
+
9
+ def _excluded_pattern():
10
+ return re.search(r'\["highway"!~"(.*)"\]$', base_filter).group(1)
11
+
12
+
13
+ def test_filter_requires_a_highway_tag_and_skips_areas():
14
+ # Overpass's !~ also matches ways without the key, so the filter must require highway itself.
15
+ assert base_filter.startswith('["highway"]["area"!~"yes"]')
16
+
17
+
18
+ def test_excluded_list_is_the_agreed_one():
19
+ assert len(EXCLUDED_HIGHWAY) == 21
20
+ assert set(EXCLUDED_HIGHWAY) == {
21
+ "footway", "cycleway", "path", "steps", "pedestrian", "bridleway", "corridor", "elevator",
22
+ "escalator", "ladder", "track", "construction", "proposed", "planned", "abandoned", "razed",
23
+ "no", "raceway", "platform", "bus_stop", "trailhead",
24
+ }
25
+
26
+
27
+ @pytest.mark.parametrize("value", EXCLUDED_HIGHWAY)
28
+ def test_filter_excludes_each_listed_value(value):
29
+ assert re.search(_excluded_pattern(), value)
30
+
31
+
32
+ @pytest.mark.parametrize("value", [
33
+ "service", "services", "busway", "bus_guideway", "road", "rest_area", "escape", "emergency_bay",
34
+ "living_street", "unclassified", "residential", "motorway_link", "footpath", "nothing",
35
+ ])
36
+ def test_filter_keeps_road_values_and_near_misses(value):
37
+ # Overpass searches the regex, so only the anchors stop "no" matching inside "nothing".
38
+ assert not re.search(_excluded_pattern(), value)
@@ -46,6 +46,36 @@ def test_stale_way_id_is_recovered_by_geometry(patched_graph):
46
46
  assert set(xd8.osmid) == {400}
47
47
 
48
48
 
49
+ def test_result_carries_the_edge_road_type(patched_graph):
50
+ out = i2o.serial(patched_graph.geojson, patched_graph.csv, "DAVIDSON")
51
+
52
+ xd8 = out[out.XDSegID == 8]
53
+ assert list(xd8.highway) == ["primary;secondary"] # edge 5-6 merges a primary and a secondary way
54
+ assert set(out[out.XDSegID == 5].highway) == {"primary"}
55
+
56
+
57
+ def test_service_road_row_carries_service(patched_graph):
58
+ # The graph is patched, so this covers the conflation path and the column. The download filter is
59
+ # covered by test_filters.py and the integration test.
60
+ out = i2o.serial(patched_graph.geojson, patched_graph.csv, "LAKE")
61
+
62
+ xd10 = out[out.XDSegID == 10]
63
+ assert _edges(xd10) == [(13, 14, 0)]
64
+ assert list(xd10.source) == ["conflation"]
65
+ assert list(xd10.highway) == ["service"]
66
+
67
+
68
+ def test_fallback_does_not_put_an_xd_on_a_service_road(patched_graph, caplog):
69
+ with caplog.at_level(logging.INFO, logger="geo_mapper_api.matching"):
70
+ out = i2o.serial(patched_graph.geojson, patched_graph.csv, "LAKE")
71
+
72
+ assert _edges(out, 11) == []
73
+ summaries = [r for r in caplog.records if hasattr(r, "fallback_rejections")]
74
+ assert len(summaries) == 1
75
+ # Edge 13-14 points north, against XD 11. Its twin 14-13 runs with XD 11 but is a service road.
76
+ assert summaries[0].fallback_rejections == {"direction": 1, "road_type": 1}
77
+
78
+
49
79
  def test_interstate_xd_is_refused_on_a_residential_street(patched_graph):
50
80
  out = i2o.serial(patched_graph.geojson, patched_graph.csv, "DAVIDSON")
51
81
  assert _edges(out, 9) == []
@@ -104,6 +134,7 @@ def test_no_matches_returns_empty_result_columns(patched_graph, threads, tmp_pat
104
134
  out = run(geojson, patched_graph.csv, "DAVIDSON")
105
135
  assert out.empty
106
136
  assert list(out.columns) == i2o.RESULT_COLUMNS
137
+ assert out["highway"].dtype == object
107
138
  assert any("no edges" in r.getMessage() for r in caplog.records)
108
139
 
109
140
 
@@ -167,3 +198,5 @@ def test_output_column_types(patched_graph, county):
167
198
  for column in ["u", "v", "key", "osmid", "XDSegID"]:
168
199
  assert out[column].dtype == "int64", (column, out[column].dtype)
169
200
  assert out["overlap_m"].dtype == "float64"
201
+ assert out["highway"].dtype == object
202
+ assert all(isinstance(value, str) for value in out["highway"])
@@ -15,7 +15,8 @@ import pytest
15
15
 
16
16
  import geo_mapper_api.converters as gma
17
17
  import geo_mapper_api.inrix_to_osm as i2o
18
- from geo_mapper_api import MatchConfig, evaluation
18
+ from geo_mapper_api import MatchConfig, evaluation, matching
19
+ from geo_mapper_api.filters import EXCLUDED_HIGHWAY
19
20
 
20
21
  DATA = Path(os.environ.get("GEO_MAPPER_TEST_DATA", ""))
21
22
  AREAS = {"downtown": "DAVIDSON", "crockett": "CROCKETT"}
@@ -59,13 +60,24 @@ def run(request):
59
60
  mp.setattr(ox.settings, "cache_folder", str(DATA / "osm_cache"))
60
61
  result = i2o.serial(geojson, csv, AREAS[area], config=CONFIG) # serial: logs stay in this process
61
62
  xds = gma.load_and_prepare_inrix_data_for_multiple_counties(geojson, [AREAS[area]])
62
- summary = evaluation.summary(result, xds, evaluation.area_edges(xds, CONFIG), CONFIG)
63
+ edges = evaluation.area_edges(xds, CONFIG) # inside the patch, so it reads the test cache
64
+ summary = evaluation.summary(result, xds, edges, CONFIG)
63
65
  finally:
64
66
  matching_logger.removeHandler(collect)
65
67
  matching_logger.setLevel(old_level)
66
68
  summary["P/N disagreements"] = sum(getattr(r, "pn_disagreements", 0) for r in collect.records)
67
69
  logger.info("%s summary: %s", area, summary)
68
- return {"area": area, "result": result, "xds": xds, "csv": csv, "summary": summary}
70
+ return {"area": area, "result": result, "xds": xds, "csv": csv, "summary": summary, "edges": edges}
71
+
72
+
73
+ def test_graph_has_only_road_types(run):
74
+ # The anchored filter removes exact values, so a raw multi-value such as "footway;steps" passes by design.
75
+ excluded = set(EXCLUDED_HIGHWAY)
76
+ for value in run["edges"]["highway"]:
77
+ ways = value if isinstance(value, list) else [value]
78
+ assert ways and all(isinstance(w, str) and w not in excluded for w in ways), value
79
+ if run["area"] == "downtown":
80
+ assert any("service" in matching.road_types(v) for v in run["edges"]["highway"])
69
81
 
70
82
 
71
83
  def test_coverage(run):
@@ -163,6 +163,40 @@ def test_road_level_rule(matching, road_name, frc, highway, allowed):
163
163
  assert matching.road_level_allows(road_name, frc, highway) is allowed
164
164
 
165
165
 
166
+ @pytest.mark.parametrize("highway, allowed", [
167
+ ("service", False),
168
+ (["service", "residential"], True),
169
+ ("residential;service", True),
170
+ ("busway", False),
171
+ ("rest_area", False),
172
+ ("escape", False),
173
+ (["busway", "service"], False),
174
+ ("residential", True),
175
+ ("motorway_link", True),
176
+ ("road", True),
177
+ ("living_street", True),
178
+ (float("nan"), False),
179
+ ])
180
+ def test_fallback_type_rule(matching, highway, allowed):
181
+ assert matching.fallback_type_allows(highway) is allowed
182
+
183
+
184
+ @pytest.mark.parametrize("highway, label", [
185
+ ("primary", "primary"),
186
+ (["service", "residential"], "residential;service"),
187
+ (["primary", "primary"], "primary"),
188
+ ("service;residential", "residential;service"),
189
+ ])
190
+ def test_highway_label(matching, highway, label):
191
+ assert matching.highway_label(highway) == label
192
+
193
+
194
+ @pytest.mark.parametrize("highway", [float("nan"), None, "", []])
195
+ def test_highway_label_refuses_an_edge_without_a_road_type(matching, highway):
196
+ with pytest.raises(ValueError, match="no OSM highway tag"):
197
+ matching.highway_label(highway)
198
+
199
+
166
200
  @pytest.mark.parametrize("oneway, reversed_, two_way", [
167
201
  (False, False, True),
168
202
  (np.bool_(False), np.bool_(True), True),
@@ -216,6 +250,13 @@ def test_fallback_refuses_an_interstate_xd_on_a_residential_edge(matching, confi
216
250
  assert rejected == {"road_level": 1}
217
251
 
218
252
 
253
+ def test_fallback_refuses_a_service_edge(matching, config):
254
+ edges, xds = fallback_inputs("DELTA ROAD", 4, LineString([(10, 1), (90, 1)]), "service")
255
+ rows, rejected = matching.geometry_fallback(edges, xds, set(), config)
256
+ assert rows.empty
257
+ assert rejected == {"road_type": 1}
258
+
259
+
219
260
  def test_fallback_accepts_a_ramp_xd_on_a_motorway_link(matching, config):
220
261
  edges, xds = fallback_inputs("999X", 4, LineString([(10, 1), (90, 1)]), "motorway_link")
221
262
  rows, rejected = matching.geometry_fallback(edges, xds, set(), config)
@@ -1,4 +0,0 @@
1
- base_filter = ('["highway"!~"cycleway|footway|path|pedestrian|'
2
- 'steps|service|track|construction|bridleway|'
3
- 'corridor|elevator|escalator|proposed|'
4
- 'rest_area|escape|emergency_bay|bus_guideway"]')
File without changes