geo-mapper-api 0.1.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.
- geo_mapper_api-0.1.1/PKG-INFO +93 -0
- geo_mapper_api-0.1.1/README.md +76 -0
- geo_mapper_api-0.1.1/pyproject.toml +26 -0
- geo_mapper_api-0.1.1/setup.cfg +4 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api/__init__.py +0 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api/converters.py +299 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api/filters.py +4 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api/inrix_to_osm.py +102 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api.egg-info/PKG-INFO +93 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api.egg-info/SOURCES.txt +12 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api.egg-info/dependency_links.txt +1 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api.egg-info/requires.txt +9 -0
- geo_mapper_api-0.1.1/src/geo_mapper_api.egg-info/top_level.txt +1 -0
- geo_mapper_api-0.1.1/tests/test_run.py +12 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: geo_mapper_api
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: A simple API for matching geospatial data to OSM IDs
|
|
5
|
+
Author-email: JP Talusan <jptalusan@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/jptalusan/geospatial_mapper
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: pandas<=1.4.4
|
|
10
|
+
Requires-Dist: geopandas<=0.12.2
|
|
11
|
+
Requires-Dist: numpy>=1.22.4
|
|
12
|
+
Requires-Dist: osmnx>=1.9.4
|
|
13
|
+
Requires-Dist: fiona==1.9.6
|
|
14
|
+
Requires-Dist: pytest
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest; extra == "dev"
|
|
17
|
+
|
|
18
|
+
# Setup
|
|
19
|
+
This requires `python>=3.9` but pretty specific versions of packages. If this fails, try to create a new virtual environment with python 3.9 specifically for this package.
|
|
20
|
+
```
|
|
21
|
+
pip install geospatial_mapper
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
# Requirements
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
This conflation `csv` should have the following features:
|
|
28
|
+
| Feature | Type | Example |
|
|
29
|
+
| ----------------------- | ------- | --------- |
|
|
30
|
+
| XDSegID | Integer | 136894283 |
|
|
31
|
+
| OSMWayIDs | Integer | 19659968 |
|
|
32
|
+
| OSMWayDirections | String | N |
|
|
33
|
+
| WayStartOffset\_m | Float | 1077.78 |
|
|
34
|
+
| WayEndOffset\_m | Float | 1851.31 |
|
|
35
|
+
| WayStartOffset\_percent | Float | 33.706 |
|
|
36
|
+
| WayEndOffset\_percent | Float | 57.897 |
|
|
37
|
+
|
|
38
|
+
While the `geojson` data should have the following features:
|
|
39
|
+
| Feature | Type | Example |
|
|
40
|
+
| ---------- | -------- | ------------------ |
|
|
41
|
+
| OID | Integer | 7931440 |
|
|
42
|
+
| XDSegID | Integer | 156418860 |
|
|
43
|
+
| PreviousXD | Float | nan |
|
|
44
|
+
| NextXDSegI | Float | 395960459.0 |
|
|
45
|
+
| FRC | Integer | 4 |
|
|
46
|
+
| RoadNumber | Float | nan |
|
|
47
|
+
| RoadName | String | DRHESSRD |
|
|
48
|
+
| LinearID | Float | nan |
|
|
49
|
+
| Country | String | UNITEDSTATES |
|
|
50
|
+
| State | String | TENNESSEE |
|
|
51
|
+
| County | String | HAYWOOD |
|
|
52
|
+
| District | Float | nan |
|
|
53
|
+
| PostalCode | String | 38006 |
|
|
54
|
+
| Miles | Float | 0.5902665205613952 |
|
|
55
|
+
| Lanes | Float | 1.0 |
|
|
56
|
+
| SlipRoad | Integer | 0 |
|
|
57
|
+
| SpecialRoa | Float | nan |
|
|
58
|
+
| RoadList | String | DRHESSRD |
|
|
59
|
+
| StartLat | Float | 35.67248 |
|
|
60
|
+
| StartLong | Float | -89.14147 |
|
|
61
|
+
| EndLat | Float | 35.666218484838986 |
|
|
62
|
+
| EndLong | Float | -89.13571015096953 |
|
|
63
|
+
| Bearing | String | S |
|
|
64
|
+
| XDGroup | Integer | 2013963 |
|
|
65
|
+
| ShapeSRID | Integer | 4326 |
|
|
66
|
+
| geometry | Geometry | LINESTRING |
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# Usage
|
|
70
|
+
As long as you have both the maprelease-osmconflation and maprelease-geojson for a particular area, then it should just work. It requires the county name.
|
|
71
|
+
```bash
|
|
72
|
+
DATA_DIR = "./tests/data"
|
|
73
|
+
geojson_path = os.path.join(DATA_DIR, 'maprelease-geojson.geojson')
|
|
74
|
+
csv_path = os.path.join(DATA_DIR, 'maprelease-osmconflation.csv')
|
|
75
|
+
county_name = ['CROCKETT']
|
|
76
|
+
df = parallel(geojson_path, csv_path, county_name, threshold_distance=25)
|
|
77
|
+
```
|
|
78
|
+
`df` should have a column named county for each of the specified county and then the mapping, see the following example.
|
|
79
|
+
| Feature | Type | Example |
|
|
80
|
+
|-------------------|----------|-------------------------------------------------------------------------|
|
|
81
|
+
| v | int | 202619796 |
|
|
82
|
+
| key | int | 202705554 |
|
|
83
|
+
| osmid | int | 0 |
|
|
84
|
+
| XDSegID | int | 19495638 |
|
|
85
|
+
| osm_geom | geometry | LINESTRING (-9927715.889573382 4219197.2535342...) |
|
|
86
|
+
| inrix_geom | geometry | LINESTRING (-9927119.795074416 4219027.3303308...) |
|
|
87
|
+
| distance | float | 0.000000 |
|
|
88
|
+
| within_threshold | bool | True |
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Development
|
|
92
|
+
Test data might be proprietary but these are just the maprelease data from Inrix.
|
|
93
|
+
Please the csv and geojson in the `tests/data` folder and name them `test.csv` and `test.geojson`. Pytest should succeed.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Setup
|
|
2
|
+
This requires `python>=3.9` but pretty specific versions of packages. If this fails, try to create a new virtual environment with python 3.9 specifically for this package.
|
|
3
|
+
```
|
|
4
|
+
pip install geospatial_mapper
|
|
5
|
+
```
|
|
6
|
+
|
|
7
|
+
# Requirements
|
|
8
|
+
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.
|
|
9
|
+
|
|
10
|
+
This conflation `csv` should have the following features:
|
|
11
|
+
| Feature | Type | Example |
|
|
12
|
+
| ----------------------- | ------- | --------- |
|
|
13
|
+
| XDSegID | Integer | 136894283 |
|
|
14
|
+
| OSMWayIDs | Integer | 19659968 |
|
|
15
|
+
| OSMWayDirections | String | N |
|
|
16
|
+
| WayStartOffset\_m | Float | 1077.78 |
|
|
17
|
+
| WayEndOffset\_m | Float | 1851.31 |
|
|
18
|
+
| WayStartOffset\_percent | Float | 33.706 |
|
|
19
|
+
| WayEndOffset\_percent | Float | 57.897 |
|
|
20
|
+
|
|
21
|
+
While the `geojson` data should have the following features:
|
|
22
|
+
| Feature | Type | Example |
|
|
23
|
+
| ---------- | -------- | ------------------ |
|
|
24
|
+
| OID | Integer | 7931440 |
|
|
25
|
+
| XDSegID | Integer | 156418860 |
|
|
26
|
+
| PreviousXD | Float | nan |
|
|
27
|
+
| NextXDSegI | Float | 395960459.0 |
|
|
28
|
+
| FRC | Integer | 4 |
|
|
29
|
+
| RoadNumber | Float | nan |
|
|
30
|
+
| RoadName | String | DRHESSRD |
|
|
31
|
+
| LinearID | Float | nan |
|
|
32
|
+
| Country | String | UNITEDSTATES |
|
|
33
|
+
| State | String | TENNESSEE |
|
|
34
|
+
| County | String | HAYWOOD |
|
|
35
|
+
| District | Float | nan |
|
|
36
|
+
| PostalCode | String | 38006 |
|
|
37
|
+
| Miles | Float | 0.5902665205613952 |
|
|
38
|
+
| Lanes | Float | 1.0 |
|
|
39
|
+
| SlipRoad | Integer | 0 |
|
|
40
|
+
| SpecialRoa | Float | nan |
|
|
41
|
+
| RoadList | String | DRHESSRD |
|
|
42
|
+
| StartLat | Float | 35.67248 |
|
|
43
|
+
| StartLong | Float | -89.14147 |
|
|
44
|
+
| EndLat | Float | 35.666218484838986 |
|
|
45
|
+
| EndLong | Float | -89.13571015096953 |
|
|
46
|
+
| Bearing | String | S |
|
|
47
|
+
| XDGroup | Integer | 2013963 |
|
|
48
|
+
| ShapeSRID | Integer | 4326 |
|
|
49
|
+
| geometry | Geometry | LINESTRING |
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Usage
|
|
53
|
+
As long as you have both the maprelease-osmconflation and maprelease-geojson for a particular area, then it should just work. It requires the county name.
|
|
54
|
+
```bash
|
|
55
|
+
DATA_DIR = "./tests/data"
|
|
56
|
+
geojson_path = os.path.join(DATA_DIR, 'maprelease-geojson.geojson')
|
|
57
|
+
csv_path = os.path.join(DATA_DIR, 'maprelease-osmconflation.csv')
|
|
58
|
+
county_name = ['CROCKETT']
|
|
59
|
+
df = parallel(geojson_path, csv_path, county_name, threshold_distance=25)
|
|
60
|
+
```
|
|
61
|
+
`df` should have a column named county for each of the specified county and then the mapping, see the following example.
|
|
62
|
+
| Feature | Type | Example |
|
|
63
|
+
|-------------------|----------|-------------------------------------------------------------------------|
|
|
64
|
+
| v | int | 202619796 |
|
|
65
|
+
| key | int | 202705554 |
|
|
66
|
+
| osmid | int | 0 |
|
|
67
|
+
| XDSegID | int | 19495638 |
|
|
68
|
+
| osm_geom | geometry | LINESTRING (-9927715.889573382 4219197.2535342...) |
|
|
69
|
+
| inrix_geom | geometry | LINESTRING (-9927119.795074416 4219027.3303308...) |
|
|
70
|
+
| distance | float | 0.000000 |
|
|
71
|
+
| within_threshold | bool | True |
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# Development
|
|
75
|
+
Test data might be proprietary but these are just the maprelease data from Inrix.
|
|
76
|
+
Please the csv and geojson in the `tests/data` folder and name them `test.csv` and `test.geojson`. Pytest should succeed.
|
|
@@ -0,0 +1,26 @@
|
|
|
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.1.1"
|
|
8
|
+
description = "A simple API for matching geospatial data to OSM IDs"
|
|
9
|
+
authors = [{ name="JP Talusan", email="jptalusan@gmail.com" }]
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["pandas<=1.4.4",
|
|
13
|
+
"geopandas<=0.12.2",
|
|
14
|
+
"numpy>=1.22.4",
|
|
15
|
+
"osmnx>=1.9.4",
|
|
16
|
+
"fiona==1.9.6",
|
|
17
|
+
"pytest"]
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
dev = ["pytest"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/jptalusan/geospatial_mapper"
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
where = ["src"]
|
|
File without changes
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import geopandas as gpd
|
|
3
|
+
import numpy as np
|
|
4
|
+
import osmnx as ox
|
|
5
|
+
import math
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
warnings.filterwarnings("ignore")
|
|
9
|
+
|
|
10
|
+
custom_filter = ('["highway"!~"cycleway|footway|path|pedestrian|'
|
|
11
|
+
'steps|service|track|construction|bridleway|'
|
|
12
|
+
'corridor|elevator|escalator|proposed|'
|
|
13
|
+
'rest_area|escape|emergency_bay|bus_guideway"]')
|
|
14
|
+
|
|
15
|
+
def load_and_prepare_inrix_data(geojson_path, county_name):
|
|
16
|
+
"""Load and filter INRIX GeoDataFrame based on the specified county."""
|
|
17
|
+
inrix_df = gpd.read_file(geojson_path)
|
|
18
|
+
inrix_df.replace(to_replace='', value=np.nan, inplace=True)
|
|
19
|
+
filtered_df = inrix_df.loc[inrix_df["County"].isin([county_name])]
|
|
20
|
+
filtered_df["PreviousXD"] = pd.to_numeric(filtered_df["PreviousXD"], errors='coerce')
|
|
21
|
+
filtered_df["XDSegID"] = pd.to_numeric(filtered_df["XDSegID"], errors='coerce')
|
|
22
|
+
filtered_df["NextXDSegI"] = pd.to_numeric(filtered_df["NextXDSegI"], errors='coerce')
|
|
23
|
+
return filtered_df
|
|
24
|
+
|
|
25
|
+
def load_and_prepare_inrix_data_for_multiple_counties(geojson_path, county_names):
|
|
26
|
+
if isinstance(county_names, str):
|
|
27
|
+
county_names = [county_names]
|
|
28
|
+
"""Load and filter INRIX GeoDataFrame based on the specified counties."""
|
|
29
|
+
inrix_df = gpd.read_file(geojson_path, engine="fiona")
|
|
30
|
+
inrix_df.replace(to_replace='', value=np.nan, inplace=True)
|
|
31
|
+
filtered_df = inrix_df.loc[inrix_df["County"].isin(county_names)]
|
|
32
|
+
filtered_df["PreviousXD"] = pd.to_numeric(filtered_df["PreviousXD"], errors='coerce')
|
|
33
|
+
filtered_df["XDSegID"] = pd.to_numeric(filtered_df["XDSegID"], errors='coerce')
|
|
34
|
+
filtered_df["NextXDSegI"] = pd.to_numeric(filtered_df["NextXDSegI"], errors='coerce')
|
|
35
|
+
return filtered_df
|
|
36
|
+
|
|
37
|
+
def get_exterior_polygon(geodf):
|
|
38
|
+
"""
|
|
39
|
+
Get the exterior polygon of a GeoDataFrame containing multiple LineStrings.
|
|
40
|
+
|
|
41
|
+
Parameters:
|
|
42
|
+
geodf (GeoDataFrame): The GeoDataFrame containing the geometries.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
shapely.geometry.Polygon: The exterior polygon of the combined geometries.
|
|
46
|
+
"""
|
|
47
|
+
# Combine all the geometries into a single geometry (union)
|
|
48
|
+
combined_geom = geodf.unary_union
|
|
49
|
+
|
|
50
|
+
# Get the convex hull of the combined geometry to form an exterior polygon
|
|
51
|
+
exterior_polygon = combined_geom.convex_hull
|
|
52
|
+
|
|
53
|
+
return exterior_polygon
|
|
54
|
+
|
|
55
|
+
def get_osm_graph(polygon, custom_filter):
|
|
56
|
+
"""
|
|
57
|
+
Get OSM road network graph for the given polygon with the custom filter.
|
|
58
|
+
|
|
59
|
+
Parameters:
|
|
60
|
+
polygon (shapely.geometry.Polygon): The polygon defining the area of interest.
|
|
61
|
+
custom_filter (str): Custom filter to apply to the OSM data.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
networkx.MultiDiGraph: The road network graph for the given polygon.
|
|
65
|
+
"""
|
|
66
|
+
G = ox.graph_from_polygon(polygon, custom_filter=custom_filter, network_type='drive')
|
|
67
|
+
return G
|
|
68
|
+
|
|
69
|
+
def classify_bearing(bearing):
|
|
70
|
+
if bearing >= 337.5 or bearing < 22.5:
|
|
71
|
+
return 'N'
|
|
72
|
+
elif 22.5 <= bearing < 67.5:
|
|
73
|
+
return 'NE'
|
|
74
|
+
elif 67.5 <= bearing < 112.5:
|
|
75
|
+
return 'E'
|
|
76
|
+
elif 112.5 <= bearing < 157.5:
|
|
77
|
+
return 'SE'
|
|
78
|
+
elif 157.5 <= bearing < 202.5:
|
|
79
|
+
return 'S'
|
|
80
|
+
elif 202.5 <= bearing < 247.5:
|
|
81
|
+
return 'SW'
|
|
82
|
+
elif 247.5 <= bearing < 292.5:
|
|
83
|
+
return 'W'
|
|
84
|
+
elif 292.5 <= bearing < 337.5:
|
|
85
|
+
return 'NW'
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def calculate_bearing(point1, point2):
|
|
89
|
+
lon1, lat1 = point1
|
|
90
|
+
lon2, lat2 = point2
|
|
91
|
+
dLon = math.radians(lon2 - lon1)
|
|
92
|
+
lat1 = math.radians(lat1)
|
|
93
|
+
lat2 = math.radians(lat2)
|
|
94
|
+
x = math.sin(dLon) * math.cos(lat2)
|
|
95
|
+
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(dLon))
|
|
96
|
+
initial_bearing = math.atan2(x, y)
|
|
97
|
+
initial_bearing = math.degrees(initial_bearing)
|
|
98
|
+
compass_bearing = (initial_bearing + 360) % 360
|
|
99
|
+
return compass_bearing
|
|
100
|
+
|
|
101
|
+
def line_bearing(line):
|
|
102
|
+
point1 = (line.coords[0][0], line.coords[0][1])
|
|
103
|
+
point2 = (line.coords[-1][0], line.coords[-1][1])
|
|
104
|
+
return calculate_bearing(point1, point2)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def prepare_osmnx_inrix_data(csv_path, davidson_inrix_df):
|
|
108
|
+
"""Prepare and expand OSMNX INRIX data."""
|
|
109
|
+
osmnx_inrix = pd.read_csv(csv_path)
|
|
110
|
+
Ave_21 = osmnx_inrix[osmnx_inrix.XDSegID.isin(davidson_inrix_df['XDSegID'])].reset_index(drop=True)
|
|
111
|
+
Ave_21['OSMWayIDs'] = Ave_21['OSMWayIDs'].apply(lambda x: x.split(';'))
|
|
112
|
+
Ave_21['OSMWayDirections'] = Ave_21['OSMWayDirections'].apply(lambda x: x.split(';'))
|
|
113
|
+
Ave_21_expanded = Ave_21.explode(['OSMWayIDs', 'OSMWayDirections']).explode('OSMWayDirections')
|
|
114
|
+
Ave_21_expanded['OSMWayIDs'] = pd.to_numeric(Ave_21_expanded['OSMWayIDs'], errors='coerce')
|
|
115
|
+
return Ave_21_expanded
|
|
116
|
+
|
|
117
|
+
def merge_and_filter_inrix_osm(edges, Ave_21_expanded, davidson_inrix_df):
|
|
118
|
+
"""Merge and filter INRIX and OSM data."""
|
|
119
|
+
test = edges.reset_index().explode('osmid').sort_values(by='osmid', ascending=False).merge(
|
|
120
|
+
Ave_21_expanded, left_on='osmid', right_on='OSMWayIDs', how='inner')
|
|
121
|
+
test_inrix = test[['u', 'v','key', 'osmid', 'lanes', 'name', 'highway', 'oneway', 'reversed', 'length',
|
|
122
|
+
'geometry', 'XDSegID', 'OSMWayDirections']].merge(davidson_inrix_df,
|
|
123
|
+
left_on='XDSegID', right_on='XDSegID', how='inner',suffixes=('_osm', '_inrix'))
|
|
124
|
+
return test_inrix
|
|
125
|
+
|
|
126
|
+
def apply_bearing_classification(df):
|
|
127
|
+
"""Apply bearing calculation and classification."""
|
|
128
|
+
df['osm_line_bearing'] = df['geometry_osm'].apply(line_bearing)
|
|
129
|
+
df['compass_direction'] = df['osm_line_bearing'].apply(classify_bearing)
|
|
130
|
+
df['match'] = df.apply(lambda row: row['Bearing'] in row['compass_direction'], axis=1)
|
|
131
|
+
return df
|
|
132
|
+
|
|
133
|
+
def filter_groups_by_match(test_inrix):
|
|
134
|
+
"""Group and filter INRIX data based on match."""
|
|
135
|
+
grouped = test_inrix.groupby(['osmid', 'XDSegID'])
|
|
136
|
+
filtered_groups = []
|
|
137
|
+
unfiltered_groups = []
|
|
138
|
+
for _, group in grouped:
|
|
139
|
+
if len(group) == 1:
|
|
140
|
+
filtered_groups.append(group)
|
|
141
|
+
else:
|
|
142
|
+
filtered_groups.append(group[group['match'] == True])
|
|
143
|
+
unfiltered_groups.append(group[group['match'] == False])
|
|
144
|
+
filtered_inrix = pd.concat(filtered_groups)
|
|
145
|
+
unfiltered_inrix = pd.concat(unfiltered_groups)
|
|
146
|
+
return filtered_inrix, unfiltered_inrix
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def buffer_geometries(gdf, column_name, buffer_size):
|
|
150
|
+
"""
|
|
151
|
+
Applies a buffer to the geometries in a GeoDataFrame.
|
|
152
|
+
|
|
153
|
+
Parameters:
|
|
154
|
+
- gdf: GeoDataFrame containing the geometries.
|
|
155
|
+
- column_name: The name of the geometry column to buffer.
|
|
156
|
+
- buffer_size: The buffer size to apply.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
- GeoDataFrame with buffered geometries.
|
|
160
|
+
"""
|
|
161
|
+
buffered_gdf = gdf.copy()
|
|
162
|
+
buffered_gdf[column_name] = buffered_gdf[column_name].buffer(buffer_size)
|
|
163
|
+
return buffered_gdf
|
|
164
|
+
|
|
165
|
+
def find_overlapping_geometries(group_df,gdf_osm, gdf_inrix, gdf_nodes):
|
|
166
|
+
"""
|
|
167
|
+
Finds overlapping geometries between OSM, INRIX, and nodes data.
|
|
168
|
+
|
|
169
|
+
Parameters:
|
|
170
|
+
- gdf_osm: GeoDataFrame containing OSM data.
|
|
171
|
+
- gdf_inrix: GeoDataFrame containing INRIX data.
|
|
172
|
+
- gdf_nodes: GeoDataFrame containing nodes data.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
- DataFrame of overlapping geometries.
|
|
176
|
+
"""
|
|
177
|
+
buffered_gdf_osm = buffer_geometries(gdf_osm, 'geometry', 1e-4)
|
|
178
|
+
buffered_gdf_inrix = buffer_geometries(gdf_inrix, 'geometry_inrix_copy', 1e-6)
|
|
179
|
+
buffered_gdf_nodes = buffer_geometries(gdf_nodes, 'geometry', 1e-3)
|
|
180
|
+
|
|
181
|
+
overlapping_nodes = gpd.sjoin(buffered_gdf_nodes, buffered_gdf_inrix, how='inner', predicate='intersects')
|
|
182
|
+
|
|
183
|
+
if len(overlapping_nodes) == 0:
|
|
184
|
+
buffered_gdf_inrix = buffer_geometries(gdf_inrix, 'geometry_inrix_copy', 1e-4)
|
|
185
|
+
overlapping_nodes = gpd.sjoin(buffered_gdf_osm, buffered_gdf_inrix, how='inner', predicate='intersects')
|
|
186
|
+
overlapping_nodes = overlapping_nodes[['u', 'v','key', 'osmid', 'XDSegID', 'geometry', 'geometry_inrix', 'osm_line_bearing', 'Bearing', 'compass_direction']].drop_duplicates().reset_index(drop=True)
|
|
187
|
+
overlapping_nodes = group_df[group_df.XDSegID.isin(overlapping_nodes.XDSegID)][['u', 'v','key', 'osmid', 'XDSegID', 'geometry', 'geometry_inrix', 'osm_line_bearing', 'Bearing', 'compass_direction']].drop_duplicates().reset_index(drop=True)
|
|
188
|
+
else:
|
|
189
|
+
overlapping_nodes = overlapping_nodes.drop_duplicates().reset_index(drop=True)
|
|
190
|
+
overlapping_nodes = pd.merge(overlapping_nodes[['osmid', 'XDSegID']], overlapping_nodes[['osmid', 'XDSegID']], on='XDSegID', how='inner', suffixes=('_u', '_v'))
|
|
191
|
+
overlapping_nodes = overlapping_nodes[(overlapping_nodes['osmid_u'] != overlapping_nodes['osmid_v'])]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if len(overlapping_nodes) == 0:
|
|
195
|
+
buffered_gdf_inrix = buffer_geometries(gdf_inrix, 'geometry_inrix_copy', 1e-4)
|
|
196
|
+
overlapping_nodes = gpd.sjoin(buffered_gdf_osm, buffered_gdf_inrix, how='inner', predicate='intersects')
|
|
197
|
+
overlapping_nodes = overlapping_nodes[['u', 'v','key', 'osmid', 'XDSegID', 'geometry', 'geometry_inrix', 'osm_line_bearing', 'Bearing', 'compass_direction']].drop_duplicates().reset_index(drop=True)
|
|
198
|
+
overlapping_nodes = group_df[group_df.XDSegID.isin(overlapping_nodes.XDSegID)][['u', 'v','key', 'osmid', 'XDSegID', 'geometry', 'geometry_inrix', 'osm_line_bearing', 'Bearing', 'compass_direction']].drop_duplicates().reset_index(drop=True)
|
|
199
|
+
else:
|
|
200
|
+
overlapping_nodes = group_df[group_df.XDSegID.isin(overlapping_nodes.XDSegID)][['u', 'v','key', 'osmid', 'XDSegID', 'geometry', 'geometry_inrix', 'osm_line_bearing', 'Bearing', 'compass_direction']].drop_duplicates().reset_index(drop=True)
|
|
201
|
+
|
|
202
|
+
return overlapping_nodes
|
|
203
|
+
|
|
204
|
+
def process_top_groups(grouped_data, nodes):
|
|
205
|
+
"""
|
|
206
|
+
Processes the top groups and finds overlapping geometries.
|
|
207
|
+
|
|
208
|
+
Parameters:
|
|
209
|
+
- grouped_data: Grouped DataFrame containing the top groups.
|
|
210
|
+
- nodes: GeoDataFrame containing nodes data.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
- Concatenated DataFrame of all overlapping geometries.
|
|
214
|
+
"""
|
|
215
|
+
all_overlapping_geometries = []
|
|
216
|
+
|
|
217
|
+
for group_name, group_df in grouped_data:
|
|
218
|
+
gdf_osm = gpd.GeoDataFrame(group_df.drop(columns=['XDSegID', 'geometry_inrix'], axis=1), geometry='geometry')
|
|
219
|
+
gdf_inrix = gpd.GeoDataFrame(group_df[['XDSegID', 'geometry_inrix']], geometry='geometry_inrix')
|
|
220
|
+
gdf_inrix['geometry_inrix_copy'] = gdf_inrix['geometry_inrix']
|
|
221
|
+
gdf_inrix.set_geometry('geometry_inrix_copy', inplace=True)
|
|
222
|
+
gdf_nodes = gpd.GeoDataFrame(nodes[nodes.index.isin([group_name[0], group_name[1]])].reset_index(), geometry='geometry')
|
|
223
|
+
|
|
224
|
+
overlapping_geometries = find_overlapping_geometries(group_df,gdf_osm, gdf_inrix, gdf_nodes)
|
|
225
|
+
all_overlapping_geometries.append(overlapping_geometries)
|
|
226
|
+
|
|
227
|
+
return pd.concat(all_overlapping_geometries, ignore_index=True)
|
|
228
|
+
|
|
229
|
+
def reproject_geometry(gdf, geom_column, target_crs="EPSG:3857"):
|
|
230
|
+
"""
|
|
231
|
+
Reproject a specific geometry column in a GeoDataFrame to a coordinate system using meters.
|
|
232
|
+
|
|
233
|
+
Parameters:
|
|
234
|
+
- gdf: The input GeoDataFrame with CRS 4326.
|
|
235
|
+
- geom_column: The name of the geometry column to reproject.
|
|
236
|
+
- target_crs: The target CRS for the projection (default is EPSG 3857).
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
- GeoDataFrame: The GeoDataFrame with the specified geometry column reprojected.
|
|
240
|
+
"""
|
|
241
|
+
gdf = gdf.copy()
|
|
242
|
+
gdf = gdf.set_geometry(geom_column).to_crs(target_crs)
|
|
243
|
+
return gdf
|
|
244
|
+
|
|
245
|
+
def plot_matched_geometry(df, geometry_column, title):
|
|
246
|
+
"""Plot the matched geometries with map tiles using contextily."""
|
|
247
|
+
gdf = gpd.GeoDataFrame(df, geometry=gpd.GeoSeries(df[geometry_column]))
|
|
248
|
+
gdf = gdf.to_crs(epsg=3857)
|
|
249
|
+
|
|
250
|
+
def calculate_nearest_distance(osm_geom, inrix_geom):
|
|
251
|
+
"""
|
|
252
|
+
Calculate the nearest distance between an OSM edge and an INRIX segment.
|
|
253
|
+
|
|
254
|
+
Parameters:
|
|
255
|
+
- osm_geom: Geometry of the OSM edge (LineString).
|
|
256
|
+
- inrix_geom: Geometry of the INRIX segment (LineString).
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
- float: The minimum distance between the OSM edge and the INRIX segment.
|
|
260
|
+
"""
|
|
261
|
+
return osm_geom.distance(inrix_geom)
|
|
262
|
+
|
|
263
|
+
def check_osm_inrix_proximity(test_data, threshold):
|
|
264
|
+
"""
|
|
265
|
+
Check the proximity of OSM edges to their mapped INRIX segments.
|
|
266
|
+
|
|
267
|
+
Parameters:
|
|
268
|
+
- test_data: DataFrame containing OSM edges and mapped INRIX segments.
|
|
269
|
+
- threshold: Maximum acceptable distance between OSM edge and INRIX segment in meters.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
- DataFrame: Results with calculated distances and match status.
|
|
273
|
+
"""
|
|
274
|
+
results = []
|
|
275
|
+
|
|
276
|
+
for index, row in test_data.iterrows():
|
|
277
|
+
osm_geom = row['geometry']
|
|
278
|
+
inrix_geom = row['geometry_inrix']
|
|
279
|
+
|
|
280
|
+
# Calculate the nearest distance between the OSM edge and INRIX segment
|
|
281
|
+
distance = calculate_nearest_distance(osm_geom, inrix_geom)
|
|
282
|
+
|
|
283
|
+
# Check if the distance is within the acceptable threshold
|
|
284
|
+
is_within_threshold = distance <= threshold
|
|
285
|
+
|
|
286
|
+
results.append({
|
|
287
|
+
'u': row['u'],
|
|
288
|
+
'v': row['v'],
|
|
289
|
+
'key': row['key'],
|
|
290
|
+
'osmid': row['osmid'],
|
|
291
|
+
'XDSegID': row['XDSegID'],
|
|
292
|
+
'osm_geom': osm_geom,
|
|
293
|
+
'inrix_geom': inrix_geom,
|
|
294
|
+
'distance': distance,
|
|
295
|
+
'within_threshold': is_within_threshold
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
return pd.DataFrame(results)
|
|
299
|
+
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import geo_mapper_api.converters as gma
|
|
2
|
+
import geo_mapper_api.filters as filters
|
|
3
|
+
import osmnx as ox
|
|
4
|
+
import geopandas as gpd
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
import concurrent.futures
|
|
8
|
+
|
|
9
|
+
def process_county(csv_path, inrix_df, county_name, threshold_distance=25.0):
|
|
10
|
+
try:
|
|
11
|
+
# Load and filter INRIX data
|
|
12
|
+
tdf = inrix_df.loc[inrix_df["County"].isin([county_name])]
|
|
13
|
+
tdf = tdf.copy(deep=True)
|
|
14
|
+
polygon = gma.get_exterior_polygon(tdf)
|
|
15
|
+
# Get OSM graph
|
|
16
|
+
polygon= gma.get_exterior_polygon(tdf)
|
|
17
|
+
G = gma.get_osm_graph(polygon, filters.base_filter)
|
|
18
|
+
# Get nodes and edges
|
|
19
|
+
nodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)
|
|
20
|
+
# Prepare OSMNX INRIX data
|
|
21
|
+
haywood_osm = gma.prepare_osmnx_inrix_data(csv_path, tdf)
|
|
22
|
+
# Merge and filter INRIX and OSM data
|
|
23
|
+
merged_osm_inrix = gma.merge_and_filter_inrix_osm(edges, haywood_osm, tdf)
|
|
24
|
+
|
|
25
|
+
# Apply bearing classification
|
|
26
|
+
merged_osm_inrix = gma.apply_bearing_classification(merged_osm_inrix)
|
|
27
|
+
|
|
28
|
+
# Filter groups by match
|
|
29
|
+
filtered_osm_inrix, unfiltered__osm_inrix = gma.filter_groups_by_match(merged_osm_inrix)
|
|
30
|
+
# Plot the results
|
|
31
|
+
gma.plot_matched_geometry(filtered_osm_inrix ,'geometry_osm', 'Matched Geometry ')
|
|
32
|
+
gma.plot_matched_geometry(merged_osm_inrix, 'geometry_inrix', 'Inrix Geometry ')
|
|
33
|
+
gma.plot_matched_geometry(edges, 'geometry', 'OSM Geometry ')
|
|
34
|
+
|
|
35
|
+
# Group by 'u', 'v', and 'geometry'
|
|
36
|
+
grouped = filtered_osm_inrix.groupby(['u', 'v','key'])
|
|
37
|
+
|
|
38
|
+
# Process the top groups and find overlapping geometries
|
|
39
|
+
all_overlapping_geometries = gma.process_top_groups(grouped, nodes)
|
|
40
|
+
|
|
41
|
+
# Reproject both geometry columns to a metric CRS (e.g., EPSG 3857 for Web Mercator)
|
|
42
|
+
merged_osm_inrix = gpd.GeoDataFrame(all_overlapping_geometries.copy(),geometry='geometry')
|
|
43
|
+
merged_osm_inrix = gma.reproject_geometry(merged_osm_inrix, 'geometry')
|
|
44
|
+
merged_osm_inrix = gma.reproject_geometry(merged_osm_inrix, 'geometry_inrix')
|
|
45
|
+
|
|
46
|
+
# Define the acceptable threshold distance in meters
|
|
47
|
+
threshold_distance = 25.0 # 5 meters
|
|
48
|
+
|
|
49
|
+
# Calculate and check distances
|
|
50
|
+
proximity_results = gma.check_osm_inrix_proximity(merged_osm_inrix, threshold_distance)
|
|
51
|
+
|
|
52
|
+
# outliers = proximity_results[~proximity_results['within_threshold']]
|
|
53
|
+
|
|
54
|
+
prox = proximity_results[proximity_results['within_threshold']]
|
|
55
|
+
prox['county'] = county_name # Add county name to results
|
|
56
|
+
print(county_name)
|
|
57
|
+
print(prox.shape)
|
|
58
|
+
return prox
|
|
59
|
+
|
|
60
|
+
except Exception as e:
|
|
61
|
+
print(f"Error processing {county_name}: {e}")
|
|
62
|
+
return pd.DataFrame() # Return empty DataFrame on failure
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parallel(geojson_path, csv_path, counties, threshold_distance):
|
|
66
|
+
all_results = []
|
|
67
|
+
|
|
68
|
+
all_counties_df = gma.load_and_prepare_inrix_data_for_multiple_counties(geojson_path, counties)
|
|
69
|
+
with concurrent.futures.ProcessPoolExecutor() as executor:
|
|
70
|
+
futures = {
|
|
71
|
+
executor.submit(process_county, csv_path, all_counties_df, county, threshold_distance): county
|
|
72
|
+
for county in counties
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
for future in concurrent.futures.as_completed(futures):
|
|
76
|
+
result = future.result()
|
|
77
|
+
if not result.empty:
|
|
78
|
+
all_results.append(result)
|
|
79
|
+
|
|
80
|
+
if all_results:
|
|
81
|
+
return pd.concat(all_results, ignore_index=True)
|
|
82
|
+
else:
|
|
83
|
+
print("No results returned.")
|
|
84
|
+
return pd.DataFrame()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def serial(geojson_path, csv_path, counties, threshold_distance):
|
|
88
|
+
|
|
89
|
+
if isinstance(counties, str):
|
|
90
|
+
counties = [counties]
|
|
91
|
+
all_results = []
|
|
92
|
+
|
|
93
|
+
all_counties_df = gma.load_and_prepare_inrix_data_for_multiple_counties(geojson_path, counties)
|
|
94
|
+
|
|
95
|
+
for county_name in counties:
|
|
96
|
+
print(f"Processing county: {county_name}")
|
|
97
|
+
# Load and filter INRIX data
|
|
98
|
+
prox = process_county(csv_path, all_counties_df, county_name, threshold_distance)
|
|
99
|
+
all_results.append(prox)
|
|
100
|
+
|
|
101
|
+
all_results = pd.concat(all_results, ignore_index=True)
|
|
102
|
+
return all_results
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: geo_mapper_api
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: A simple API for matching geospatial data to OSM IDs
|
|
5
|
+
Author-email: JP Talusan <jptalusan@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/jptalusan/geospatial_mapper
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: pandas<=1.4.4
|
|
10
|
+
Requires-Dist: geopandas<=0.12.2
|
|
11
|
+
Requires-Dist: numpy>=1.22.4
|
|
12
|
+
Requires-Dist: osmnx>=1.9.4
|
|
13
|
+
Requires-Dist: fiona==1.9.6
|
|
14
|
+
Requires-Dist: pytest
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest; extra == "dev"
|
|
17
|
+
|
|
18
|
+
# Setup
|
|
19
|
+
This requires `python>=3.9` but pretty specific versions of packages. If this fails, try to create a new virtual environment with python 3.9 specifically for this package.
|
|
20
|
+
```
|
|
21
|
+
pip install geospatial_mapper
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
# Requirements
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
This conflation `csv` should have the following features:
|
|
28
|
+
| Feature | Type | Example |
|
|
29
|
+
| ----------------------- | ------- | --------- |
|
|
30
|
+
| XDSegID | Integer | 136894283 |
|
|
31
|
+
| OSMWayIDs | Integer | 19659968 |
|
|
32
|
+
| OSMWayDirections | String | N |
|
|
33
|
+
| WayStartOffset\_m | Float | 1077.78 |
|
|
34
|
+
| WayEndOffset\_m | Float | 1851.31 |
|
|
35
|
+
| WayStartOffset\_percent | Float | 33.706 |
|
|
36
|
+
| WayEndOffset\_percent | Float | 57.897 |
|
|
37
|
+
|
|
38
|
+
While the `geojson` data should have the following features:
|
|
39
|
+
| Feature | Type | Example |
|
|
40
|
+
| ---------- | -------- | ------------------ |
|
|
41
|
+
| OID | Integer | 7931440 |
|
|
42
|
+
| XDSegID | Integer | 156418860 |
|
|
43
|
+
| PreviousXD | Float | nan |
|
|
44
|
+
| NextXDSegI | Float | 395960459.0 |
|
|
45
|
+
| FRC | Integer | 4 |
|
|
46
|
+
| RoadNumber | Float | nan |
|
|
47
|
+
| RoadName | String | DRHESSRD |
|
|
48
|
+
| LinearID | Float | nan |
|
|
49
|
+
| Country | String | UNITEDSTATES |
|
|
50
|
+
| State | String | TENNESSEE |
|
|
51
|
+
| County | String | HAYWOOD |
|
|
52
|
+
| District | Float | nan |
|
|
53
|
+
| PostalCode | String | 38006 |
|
|
54
|
+
| Miles | Float | 0.5902665205613952 |
|
|
55
|
+
| Lanes | Float | 1.0 |
|
|
56
|
+
| SlipRoad | Integer | 0 |
|
|
57
|
+
| SpecialRoa | Float | nan |
|
|
58
|
+
| RoadList | String | DRHESSRD |
|
|
59
|
+
| StartLat | Float | 35.67248 |
|
|
60
|
+
| StartLong | Float | -89.14147 |
|
|
61
|
+
| EndLat | Float | 35.666218484838986 |
|
|
62
|
+
| EndLong | Float | -89.13571015096953 |
|
|
63
|
+
| Bearing | String | S |
|
|
64
|
+
| XDGroup | Integer | 2013963 |
|
|
65
|
+
| ShapeSRID | Integer | 4326 |
|
|
66
|
+
| geometry | Geometry | LINESTRING |
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# Usage
|
|
70
|
+
As long as you have both the maprelease-osmconflation and maprelease-geojson for a particular area, then it should just work. It requires the county name.
|
|
71
|
+
```bash
|
|
72
|
+
DATA_DIR = "./tests/data"
|
|
73
|
+
geojson_path = os.path.join(DATA_DIR, 'maprelease-geojson.geojson')
|
|
74
|
+
csv_path = os.path.join(DATA_DIR, 'maprelease-osmconflation.csv')
|
|
75
|
+
county_name = ['CROCKETT']
|
|
76
|
+
df = parallel(geojson_path, csv_path, county_name, threshold_distance=25)
|
|
77
|
+
```
|
|
78
|
+
`df` should have a column named county for each of the specified county and then the mapping, see the following example.
|
|
79
|
+
| Feature | Type | Example |
|
|
80
|
+
|-------------------|----------|-------------------------------------------------------------------------|
|
|
81
|
+
| v | int | 202619796 |
|
|
82
|
+
| key | int | 202705554 |
|
|
83
|
+
| osmid | int | 0 |
|
|
84
|
+
| XDSegID | int | 19495638 |
|
|
85
|
+
| osm_geom | geometry | LINESTRING (-9927715.889573382 4219197.2535342...) |
|
|
86
|
+
| inrix_geom | geometry | LINESTRING (-9927119.795074416 4219027.3303308...) |
|
|
87
|
+
| distance | float | 0.000000 |
|
|
88
|
+
| within_threshold | bool | True |
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Development
|
|
92
|
+
Test data might be proprietary but these are just the maprelease data from Inrix.
|
|
93
|
+
Please the csv and geojson in the `tests/data` folder and name them `test.csv` and `test.geojson`. Pytest should succeed.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/geo_mapper_api/__init__.py
|
|
4
|
+
src/geo_mapper_api/converters.py
|
|
5
|
+
src/geo_mapper_api/filters.py
|
|
6
|
+
src/geo_mapper_api/inrix_to_osm.py
|
|
7
|
+
src/geo_mapper_api.egg-info/PKG-INFO
|
|
8
|
+
src/geo_mapper_api.egg-info/SOURCES.txt
|
|
9
|
+
src/geo_mapper_api.egg-info/dependency_links.txt
|
|
10
|
+
src/geo_mapper_api.egg-info/requires.txt
|
|
11
|
+
src/geo_mapper_api.egg-info/top_level.txt
|
|
12
|
+
tests/test_run.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
geo_mapper_api
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from geo_mapper_api.inrix_to_osm import parallel
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
def test_parallel():
|
|
5
|
+
print("Running inrix to osm mapping...")
|
|
6
|
+
DATA_DIR = "./tests/data"
|
|
7
|
+
geojson_path = os.path.join(DATA_DIR, 'test.geojson')
|
|
8
|
+
csv_path = os.path.join(DATA_DIR, 'test.csv')
|
|
9
|
+
county_name = ['CROCKETT']
|
|
10
|
+
df = parallel(geojson_path, csv_path, county_name, threshold_distance=25)
|
|
11
|
+
assert not df.empty, "DataFrame should not be empty"
|
|
12
|
+
assert df.county.unique()[0] == 'CROCKETT', "County name should be CROCKETT"
|