geo-mapper-api 0.1.2__tar.gz → 0.3.0__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.
- geo_mapper_api-0.3.0/PKG-INFO +197 -0
- geo_mapper_api-0.3.0/README.md +180 -0
- geo_mapper_api-0.3.0/pyproject.toml +31 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api/__init__.py +3 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api/config.py +68 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api/converters.py +111 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api/evaluation.py +121 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api/inrix_to_osm.py +127 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api/matching.py +301 -0
- geo_mapper_api-0.3.0/src/geo_mapper_api.egg-info/PKG-INFO +197 -0
- {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.0}/src/geo_mapper_api.egg-info/SOURCES.txt +8 -1
- geo_mapper_api-0.3.0/src/geo_mapper_api.egg-info/requires.txt +8 -0
- geo_mapper_api-0.3.0/tests/test_config.py +101 -0
- geo_mapper_api-0.3.0/tests/test_converters.py +165 -0
- geo_mapper_api-0.3.0/tests/test_inrix_to_osm.py +169 -0
- geo_mapper_api-0.3.0/tests/test_integration.py +118 -0
- geo_mapper_api-0.3.0/tests/test_matching.py +231 -0
- geo_mapper_api-0.1.2/PKG-INFO +0 -99
- geo_mapper_api-0.1.2/README.md +0 -82
- geo_mapper_api-0.1.2/pyproject.toml +0 -26
- geo_mapper_api-0.1.2/src/geo_mapper_api/__init__.py +0 -0
- geo_mapper_api-0.1.2/src/geo_mapper_api/converters.py +0 -299
- geo_mapper_api-0.1.2/src/geo_mapper_api/inrix_to_osm.py +0 -102
- geo_mapper_api-0.1.2/src/geo_mapper_api.egg-info/PKG-INFO +0 -99
- geo_mapper_api-0.1.2/src/geo_mapper_api.egg-info/requires.txt +0 -9
- geo_mapper_api-0.1.2/tests/test_run.py +0 -12
- {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.0}/setup.cfg +0 -0
- {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.0}/src/geo_mapper_api/filters.py +0 -0
- {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.0}/src/geo_mapper_api.egg-info/dependency_links.txt +0 -0
- {geo_mapper_api-0.1.2 → geo_mapper_api-0.3.0}/src/geo_mapper_api.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: geo_mapper_api
|
|
3
|
+
Version: 0.3.0
|
|
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 the OSM way. 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
|
+
# Setup
|
|
41
|
+
This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
|
|
42
|
+
```
|
|
43
|
+
pip install geo_mapper_api
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
# Requirements
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
This conflation `csv` should have the following features:
|
|
50
|
+
| Feature | Type | Example |
|
|
51
|
+
| ----------------------- | ------- | --------- |
|
|
52
|
+
| XDSegID | Integer | 136894283 |
|
|
53
|
+
| OSMWayIDs | String | 19659968;19659970 |
|
|
54
|
+
| OSMWayDirections | String | N;N |
|
|
55
|
+
| WayStartOffset\_m | Float | 1077.78 |
|
|
56
|
+
| WayEndOffset\_m | Float | 1851.31 |
|
|
57
|
+
| WayStartOffset\_percent | Float | 33.706 |
|
|
58
|
+
| WayEndOffset\_percent | Float | 57.897 |
|
|
59
|
+
|
|
60
|
+
Only `XDSegID`, `OSMWayIDs` and `OSMWayDirections` are required. `OSMWayIDs` and `OSMWayDirections` hold `;`-separated lists of the same length.
|
|
61
|
+
|
|
62
|
+
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:
|
|
63
|
+
| Feature | Type | Example |
|
|
64
|
+
| ---------- | -------- | ------------------ |
|
|
65
|
+
| OID | Integer | 7931440 |
|
|
66
|
+
| XDSegID | Integer | 156418860 |
|
|
67
|
+
| PreviousXD | Float | nan |
|
|
68
|
+
| NextXDSegI | Float | 395960459.0 |
|
|
69
|
+
| FRC | Integer | 4 |
|
|
70
|
+
| RoadNumber | Float | nan |
|
|
71
|
+
| RoadName | String | DRHESSRD |
|
|
72
|
+
| LinearID | Float | nan |
|
|
73
|
+
| Country | String | UNITEDSTATES |
|
|
74
|
+
| State | String | TENNESSEE |
|
|
75
|
+
| County | String | HAYWOOD |
|
|
76
|
+
| District | Float | nan |
|
|
77
|
+
| PostalCode | String | 38006 |
|
|
78
|
+
| Miles | Float | 0.5902665205613952 |
|
|
79
|
+
| Lanes | Float | 1.0 |
|
|
80
|
+
| SlipRoad | Integer | 0 |
|
|
81
|
+
| SpecialRoa | Float | nan |
|
|
82
|
+
| RoadList | String | DRHESSRD |
|
|
83
|
+
| StartLat | Float | 35.67248 |
|
|
84
|
+
| StartLong | Float | -89.14147 |
|
|
85
|
+
| EndLat | Float | 35.666218484838986 |
|
|
86
|
+
| EndLong | Float | -89.13571015096953 |
|
|
87
|
+
| Bearing | String | S |
|
|
88
|
+
| XDGroup | Integer | 2013963 |
|
|
89
|
+
| ShapeSRID | Integer | 4326 |
|
|
90
|
+
| geometry | Geometry | LINESTRING |
|
|
91
|
+
|
|
92
|
+
# Usage
|
|
93
|
+
Give it the map release GeoJSON, the conflation CSV, and one or more county names. County names are matched case-insensitively.
|
|
94
|
+
```python
|
|
95
|
+
import os
|
|
96
|
+
|
|
97
|
+
from geo_mapper_api import MatchConfig, inrix_to_osm
|
|
98
|
+
|
|
99
|
+
DATA_DIR = "./data"
|
|
100
|
+
geojson_path = os.path.join(DATA_DIR, "USA_Tennessee.geojson")
|
|
101
|
+
csv_path = os.path.join(DATA_DIR, "USA_Tennessee.csv")
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
df = inrix_to_osm.parallel(geojson_path, csv_path, ["WILLIAMSON", "DAVIDSON"], config=MatchConfig())
|
|
105
|
+
df.to_csv(os.path.join(DATA_DIR, "inrix_osm.csv"), index=False)
|
|
106
|
+
```
|
|
107
|
+
`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
|
+
|
|
109
|
+
## How a match is decided
|
|
110
|
+
For each XD, an OSM edge is matched when:
|
|
111
|
+
1. it carries an OSM way that INRIX's conflation lists for the XD;
|
|
112
|
+
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
|
+
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
|
+
|
|
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.
|
|
116
|
+
|
|
117
|
+
## Settings
|
|
118
|
+
Every tunable number lives in `MatchConfig`. Distances are in meters.
|
|
119
|
+
|
|
120
|
+
| Setting | Default | Meaning |
|
|
121
|
+
|---|---|---|
|
|
122
|
+
| `band_half_width_m` | 15.0 | half-width of the band around each XD |
|
|
123
|
+
| `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 |
|
|
125
|
+
| `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
|
|
126
|
+
| `reserved_cores` | 2 | CPU cores `parallel` leaves free |
|
|
127
|
+
|
|
128
|
+
Settings can come from a TOML file of top-level keys; keys left out keep their defaults:
|
|
129
|
+
```toml
|
|
130
|
+
band_half_width_m = 20
|
|
131
|
+
min_overlap_m = 10
|
|
132
|
+
```
|
|
133
|
+
```python
|
|
134
|
+
config = MatchConfig.from_toml("matching.toml")
|
|
135
|
+
```
|
|
136
|
+
A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
|
|
137
|
+
|
|
138
|
+
## 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.
|
|
140
|
+
- 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
|
+
- 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
|
+
|
|
143
|
+
The result has one row per OSM edge and XD segment pair:
|
|
144
|
+
| Column | Type | Example |
|
|
145
|
+
|------------------|----------|-------------------------------------------|
|
|
146
|
+
| u | int | 202619796 |
|
|
147
|
+
| v | int | 202705554 |
|
|
148
|
+
| key | int | 0 |
|
|
149
|
+
| osmid | int | 19495638 |
|
|
150
|
+
| XDSegID | int | 1524404117 |
|
|
151
|
+
| osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
|
|
152
|
+
| inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
|
|
153
|
+
| overlap_m | float | 88.4 |
|
|
154
|
+
| source | str | conflation |
|
|
155
|
+
| county | str | DAVIDSON |
|
|
156
|
+
|
|
157
|
+
- `u`, `v` and `key` identify the edge in the osmnx graph.
|
|
158
|
+
- `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.
|
|
159
|
+
- Geometries are in EPSG:4326 (longitude, latitude).
|
|
160
|
+
- `overlap_m` is how far the edge runs along the XD, in meters.
|
|
161
|
+
- `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
|
|
162
|
+
- `county` holds the upper-cased county name.
|
|
163
|
+
|
|
164
|
+
# Errors
|
|
165
|
+
- `config` that isn't a `MatchConfig` raises `TypeError` before anything is read.
|
|
166
|
+
- 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.
|
|
167
|
+
- A failure while processing a county raises `RuntimeError` with a message like `county 'DAVIDSON' failed: ConnectionError: ...`.
|
|
168
|
+
|
|
169
|
+
# Logging
|
|
170
|
+
The package logs through Python's `logging` module and writes no files itself. To keep its logs:
|
|
171
|
+
```python
|
|
172
|
+
import logging
|
|
173
|
+
import os
|
|
174
|
+
|
|
175
|
+
os.makedirs("log", exist_ok=True)
|
|
176
|
+
logging.basicConfig(filename="log/geo_mapper.log", level=logging.DEBUG)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
# Development
|
|
180
|
+
```
|
|
181
|
+
python3.12 -m venv .venv
|
|
182
|
+
.venv/bin/pip install -e ".[dev]"
|
|
183
|
+
.venv/bin/pytest
|
|
184
|
+
```
|
|
185
|
+
The unit tests run on small hand-made data and need no network.
|
|
186
|
+
|
|
187
|
+
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:
|
|
188
|
+
```
|
|
189
|
+
.venv/bin/python scripts/make_test_data.py --geojson-src HOST:/path/USA_Tennessee.geojson --csv-src HOST:/path/conflation.csv
|
|
190
|
+
GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
|
|
191
|
+
```
|
|
192
|
+
The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
|
|
193
|
+
|
|
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/`.
|
|
195
|
+
|
|
196
|
+
# Releasing
|
|
197
|
+
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,180 @@
|
|
|
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 the OSM way. 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
|
+
# Setup
|
|
24
|
+
This needs Python 3.11 or later. It uses osmnx 2, geopandas 1 and pandas 2.1 or later.
|
|
25
|
+
```
|
|
26
|
+
pip install geo_mapper_api
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
# Requirements
|
|
30
|
+
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.
|
|
31
|
+
|
|
32
|
+
This conflation `csv` should have the following features:
|
|
33
|
+
| Feature | Type | Example |
|
|
34
|
+
| ----------------------- | ------- | --------- |
|
|
35
|
+
| XDSegID | Integer | 136894283 |
|
|
36
|
+
| OSMWayIDs | String | 19659968;19659970 |
|
|
37
|
+
| OSMWayDirections | String | N;N |
|
|
38
|
+
| WayStartOffset\_m | Float | 1077.78 |
|
|
39
|
+
| WayEndOffset\_m | Float | 1851.31 |
|
|
40
|
+
| WayStartOffset\_percent | Float | 33.706 |
|
|
41
|
+
| WayEndOffset\_percent | Float | 57.897 |
|
|
42
|
+
|
|
43
|
+
Only `XDSegID`, `OSMWayIDs` and `OSMWayDirections` are required. `OSMWayIDs` and `OSMWayDirections` hold `;`-separated lists of the same length.
|
|
44
|
+
|
|
45
|
+
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:
|
|
46
|
+
| Feature | Type | Example |
|
|
47
|
+
| ---------- | -------- | ------------------ |
|
|
48
|
+
| OID | Integer | 7931440 |
|
|
49
|
+
| XDSegID | Integer | 156418860 |
|
|
50
|
+
| PreviousXD | Float | nan |
|
|
51
|
+
| NextXDSegI | Float | 395960459.0 |
|
|
52
|
+
| FRC | Integer | 4 |
|
|
53
|
+
| RoadNumber | Float | nan |
|
|
54
|
+
| RoadName | String | DRHESSRD |
|
|
55
|
+
| LinearID | Float | nan |
|
|
56
|
+
| Country | String | UNITEDSTATES |
|
|
57
|
+
| State | String | TENNESSEE |
|
|
58
|
+
| County | String | HAYWOOD |
|
|
59
|
+
| District | Float | nan |
|
|
60
|
+
| PostalCode | String | 38006 |
|
|
61
|
+
| Miles | Float | 0.5902665205613952 |
|
|
62
|
+
| Lanes | Float | 1.0 |
|
|
63
|
+
| SlipRoad | Integer | 0 |
|
|
64
|
+
| SpecialRoa | Float | nan |
|
|
65
|
+
| RoadList | String | DRHESSRD |
|
|
66
|
+
| StartLat | Float | 35.67248 |
|
|
67
|
+
| StartLong | Float | -89.14147 |
|
|
68
|
+
| EndLat | Float | 35.666218484838986 |
|
|
69
|
+
| EndLong | Float | -89.13571015096953 |
|
|
70
|
+
| Bearing | String | S |
|
|
71
|
+
| XDGroup | Integer | 2013963 |
|
|
72
|
+
| ShapeSRID | Integer | 4326 |
|
|
73
|
+
| geometry | Geometry | LINESTRING |
|
|
74
|
+
|
|
75
|
+
# Usage
|
|
76
|
+
Give it the map release GeoJSON, the conflation CSV, and one or more county names. County names are matched case-insensitively.
|
|
77
|
+
```python
|
|
78
|
+
import os
|
|
79
|
+
|
|
80
|
+
from geo_mapper_api import MatchConfig, inrix_to_osm
|
|
81
|
+
|
|
82
|
+
DATA_DIR = "./data"
|
|
83
|
+
geojson_path = os.path.join(DATA_DIR, "USA_Tennessee.geojson")
|
|
84
|
+
csv_path = os.path.join(DATA_DIR, "USA_Tennessee.csv")
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
df = inrix_to_osm.parallel(geojson_path, csv_path, ["WILLIAMSON", "DAVIDSON"], config=MatchConfig())
|
|
88
|
+
df.to_csv(os.path.join(DATA_DIR, "inrix_osm.csv"), index=False)
|
|
89
|
+
```
|
|
90
|
+
`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
|
+
|
|
92
|
+
## How a match is decided
|
|
93
|
+
For each XD, an OSM edge is matched when:
|
|
94
|
+
1. it carries an OSM way that INRIX's conflation lists for the XD;
|
|
95
|
+
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
|
+
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
|
+
|
|
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.
|
|
99
|
+
|
|
100
|
+
## Settings
|
|
101
|
+
Every tunable number lives in `MatchConfig`. Distances are in meters.
|
|
102
|
+
|
|
103
|
+
| Setting | Default | Meaning |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| `band_half_width_m` | 15.0 | half-width of the band around each XD |
|
|
106
|
+
| `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 |
|
|
108
|
+
| `hull_buffer_m` | 200.0 | margin around the county's XDs for the OSM download |
|
|
109
|
+
| `reserved_cores` | 2 | CPU cores `parallel` leaves free |
|
|
110
|
+
|
|
111
|
+
Settings can come from a TOML file of top-level keys; keys left out keep their defaults:
|
|
112
|
+
```toml
|
|
113
|
+
band_half_width_m = 20
|
|
114
|
+
min_overlap_m = 10
|
|
115
|
+
```
|
|
116
|
+
```python
|
|
117
|
+
config = MatchConfig.from_toml("matching.toml")
|
|
118
|
+
```
|
|
119
|
+
A wrong type raises `TypeError` and an invalid value raises `ValueError`, both naming the setting (and the file, for `from_toml`).
|
|
120
|
+
|
|
121
|
+
## 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.
|
|
123
|
+
- 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
|
+
- 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
|
+
|
|
126
|
+
The result has one row per OSM edge and XD segment pair:
|
|
127
|
+
| Column | Type | Example |
|
|
128
|
+
|------------------|----------|-------------------------------------------|
|
|
129
|
+
| u | int | 202619796 |
|
|
130
|
+
| v | int | 202705554 |
|
|
131
|
+
| key | int | 0 |
|
|
132
|
+
| osmid | int | 19495638 |
|
|
133
|
+
| XDSegID | int | 1524404117 |
|
|
134
|
+
| osm_geom | geometry | LINESTRING (-86.7801 36.1602, ...) |
|
|
135
|
+
| inrix_geom | geometry | LINESTRING (-86.7800 36.1603, ...) |
|
|
136
|
+
| overlap_m | float | 88.4 |
|
|
137
|
+
| source | str | conflation |
|
|
138
|
+
| county | str | DAVIDSON |
|
|
139
|
+
|
|
140
|
+
- `u`, `v` and `key` identify the edge in the osmnx graph.
|
|
141
|
+
- `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.
|
|
142
|
+
- Geometries are in EPSG:4326 (longitude, latitude).
|
|
143
|
+
- `overlap_m` is how far the edge runs along the XD, in meters.
|
|
144
|
+
- `source` is `conflation` for matches through INRIX's way IDs and `geometry` for fallback matches.
|
|
145
|
+
- `county` holds the upper-cased county name.
|
|
146
|
+
|
|
147
|
+
# Errors
|
|
148
|
+
- `config` that isn't a `MatchConfig` raises `TypeError` before anything is read.
|
|
149
|
+
- 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.
|
|
150
|
+
- A failure while processing a county raises `RuntimeError` with a message like `county 'DAVIDSON' failed: ConnectionError: ...`.
|
|
151
|
+
|
|
152
|
+
# Logging
|
|
153
|
+
The package logs through Python's `logging` module and writes no files itself. To keep its logs:
|
|
154
|
+
```python
|
|
155
|
+
import logging
|
|
156
|
+
import os
|
|
157
|
+
|
|
158
|
+
os.makedirs("log", exist_ok=True)
|
|
159
|
+
logging.basicConfig(filename="log/geo_mapper.log", level=logging.DEBUG)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
# Development
|
|
163
|
+
```
|
|
164
|
+
python3.12 -m venv .venv
|
|
165
|
+
.venv/bin/pip install -e ".[dev]"
|
|
166
|
+
.venv/bin/pytest
|
|
167
|
+
```
|
|
168
|
+
The unit tests run on small hand-made data and need no network.
|
|
169
|
+
|
|
170
|
+
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:
|
|
171
|
+
```
|
|
172
|
+
.venv/bin/python scripts/make_test_data.py --geojson-src HOST:/path/USA_Tennessee.geojson --csv-src HOST:/path/conflation.csv
|
|
173
|
+
GEO_MAPPER_TEST_DATA=tests/data .venv/bin/pytest
|
|
174
|
+
```
|
|
175
|
+
The first run downloads the OSM network into `tests/data/osm_cache`. Later runs reuse it.
|
|
176
|
+
|
|
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/`.
|
|
178
|
+
|
|
179
|
+
# Releasing
|
|
180
|
+
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.0"
|
|
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,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.5
|
|
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)
|