Skip to content

UrbanAccessAnalyzer.osm_io

OpenStreetMap data ingestion, entirely into Polars.

This module is the single entry point for getting OpenStreetMap data into the package as Polars DataFrames. It replaces the previous osmnx/networkx + osmium CLI pipeline with two independent paths:

  1. Street networks (:func:load_pbf): a .osm.pbf extract is parsed directly by DuckDB's spatial extension <https://duckdb.org/docs/extensions/spatial/functions.html#st_readosm>_ (ST_ReadOSM), which streams the protobuf file straight into Arrow record batches. Polars reads those batches zero-copy (duckdb_relation.pl()), so no pandas, geopandas, osmnx or networkx object is ever created. Nodes and ways are resolved into a directed edge table (u, v, length_m, highway, oneway, geometry_wkb) using vectorised Polars list/struct expressions (tag extraction, way-to-consecutive-node-pair explosion) instead of a Python loop over ways. Edge length is computed with the haversine great-circle formula so no UTM (re)projection is needed just to route.

  2. Points of interest (:func:overpass_query and the named convenience wrappers below it, e.g. :func:schools): POI payloads from Overpass are small (hundreds to low thousands of features), so a full DuckDB pipeline buys nothing there; these keep the existing raw-HTTP-to-Overpass + osm2geojson path, but the result is converted to a Polars DataFrame with a WKB geometry column immediately, instead of a GeoDataFrame.

Sources / methodology:

  • OSM PBF structure and tag semantics: https://wiki.openstreetmap.org/wiki/PBF_Format
  • Highway tag classification for walk/bike/drive network profiles follows the same tag sets osmnx and the previous osmium filter used: https://wiki.openstreetmap.org/wiki/Key:highway
  • Great-circle (haversine) distance: d = 2r * asin(sqrt(sin²(Δφ/2) + cos(φ1)cos(φ2)sin²(Δλ/2))), r = 6371008.8 m (mean Earth radius, WGS84 authalic radius approximation).
  • Geofabrik region index: https://download.geofabrik.de/index-v1.json
  • Overpass API: https://wiki.openstreetmap.org/wiki/Overpass_API

download_geofabrik(aoi, output_folder=None, coverage_tolerance=0.0001)

Download the smallest Geofabrik region that (near-)fully covers an AOI.

Parameters:

Name Type Description Default
aoi GeoDataFrame | GeoSeries

AOI geometry, in any CRS.

required
output_folder Optional[str]

Folder to save the downloaded .osm.pbf into. If None, saves to $URBANACCESSANALYZER_CACHE_DIR/osm or, failing that, <tempdir>/urbanaccessanalyzer-cache/osm (never the CWD).

None
coverage_tolerance float

Maximum fraction of aoi's own area allowed to fall OUTSIDE a candidate region before it's rejected (aoi.difference(region).area / aoi.area <= coverage_tolerance), rather than requiring exact topological containment. Two real-world boundary sources for the "same" administrative area (e.g. Census TIGER vs. OSM/Geofabrik's own drawn state boundary) essentially never align vertex-for-vertex, so a strict region_geom.contains(aoi_geom) check routinely fails over a sliver of area that is pure boundary-simplification noise, not a real gap -- found live 2026-09-29: Census TIGER's New Mexico polygon failed strict containment against Geofabrik's own us/new-mexico region by a difference area of ~0.00024 sq degrees (a rounding-level mismatch), silently falling back to downloading the entire "United States of America" (953 MB) extract instead of New Mexico's own (a few MB) -- exactly the kind of unnecessary, oversized download this function exists to avoid, and a serious problem at national, state-by-state processing scale where the whole point is NEVER loading more than one state's/county's OSM data into memory at a time. The real New-Mexico-vs-Geofabrik mismatch measured ~7.6e-6 of the AOI's own area; default 1e-4 (0.01%) keeps a >10x margin above that observed noise level while still rejecting a region actually missing a real, substantial piece of the AOI.

0.0001

Returns:

Type Description
str

Path to the downloaded (or already-cached) .osm.pbf file.

Raises:

Type Description
ValueError

If no Geofabrik region covers the AOI within tolerance.

load_pbf(pbf_path, aoi=None, network_type='walk', bbox_margin_deg=0.02, ignore_oneway=False)

Load a street network from a .osm.pbf file directly into Polars.

Uses DuckDB's ST_ReadOSM table function to parse the PBF into Arrow, then resolves ways into a directed edge table entirely with Polars expressions (no per-way Python loop, no networkx/osmnx/geopandas).

Parameters:

Name Type Description Default
pbf_path str

Path to a local .osm.pbf file (e.g. from :func:download_geofabrik).

required
aoi Optional[GeoDataFrame | GeoSeries]

Optional AOI used to bbox-prefilter nodes before resolving ways, for speed on large regional extracts. If None, the whole file is loaded.

None
network_type str

One of "walk", "bike", "drive", "all", "walk+bike", "walk+bike+primary" (see :data:NETWORK_PROFILES).

'walk'
bbox_margin_deg float

Degrees of padding added around the AOI bounding box before filtering nodes, so edges that straddle the AOI boundary aren't dropped prematurely (final precise cropping belongs to graph_ops.crop_by_aoi).

0.02
ignore_oneway bool

If True, every kept way is emitted as a directed edge in BOTH directions regardless of its OSM oneway tag -- for walking-access graphs, where a pedestrian can generally walk against traffic direction, a vehicle-only oneway=yes should not restrict traversal. The returned oneway column still reports the original OSM tag value either way; only which direction(s) get an edge row changes. Defaults to False (the original OSM-faithful behavior), which existing drive/bike callers rely on.

False

Returns:

Name Type Description
nodes DataFrame

columns node_id (i64), lon (f64), lat (f64), one row per node referenced by a kept edge.

edges DataFrame

columns u (i64), v (i64), length_m (f64), highway (str), oneway (bool), geometry_wkb (binary), edge_uid (i64), one directed row per traversable direction (two rows per two-way segment sharing the same edge_uid, one row for a oneway=yes segment). edge_uid lets downstream code (e.g. graph_ops.simplify) recognize the forward/backward rows of the same original way segment as one edge.

Raises:

Type Description
ValueError

If network_type is not a known profile.

overpass_query(query, bounds, timeout=120, retries=5, retry_wait=10.0)

Run a raw Overpass API query and return results as a Polars DataFrame.

Parameters:

Name Type Description Default
query str

An Overpass QL query string containing a {{bbox}} placeholder (substituted with south,west,north,east).

required
bounds GeoDataFrame | GeoSeries

Geometry defining the query bounding box; the result is also spatially filtered to intersect this geometry.

required
timeout int

HTTP timeout in seconds per Overpass mirror attempt.

120
retries int

Rounds over all mirrors before giving up (public Overpass servers are often busy).

5
retry_wait float

Base wait in seconds; round k waits k * retry_wait.

10.0

Returns:

Type Description
DataFrame

A Polars DataFrame with a WKB geometry column (EPSG:4326) plus one

DataFrame

column per flattened OSM tag.

Raises:

Type Description
RuntimeError

If every Overpass mirror fails.

green_areas(bounds, min_area=200, min_width=10, buffer=5)

Fetch green-space polygons (parks, gardens, forests, grass) from OSM.

Applies an erosion-dilation-erosion sequence (shrink by min_width, grow back by buffer + min_width, shrink by buffer) to merge adjacent slivers and drop features narrower than min_width, matching common walkable-green-space definitions used in accessibility studies.

Parameters:

Name Type Description Default
bounds

AOI geometry.

required
min_area float

Minimum polygon area (m²) to keep.

200
min_width float

Minimum feature width (m) to keep (erosion radius).

10
buffer float

Extra buffer (m) applied during the dilation step.

5

Returns:

Type Description
DataFrame

Polars DataFrame with a WKB geometry column, in the CRS of bounds.

bus_stops(bounds)

Fetch bus stop points from OSM (highway=bus_stop).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

schools(bounds)

Fetch school points/polygons from OSM (amenity=school).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

healthcare(bounds)

Fetch healthcare facilities from OSM (hospitals, clinics, doctors, healthcare=*).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

groceries(bounds)

Fetch grocery/supermarket/market POIs from OSM.

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

shops(bounds)

Fetch all shop=* POIs from OSM.

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

restaurants(bounds)

Fetch restaurant/bar/pub/cafe/fast-food POIs from OSM.

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

libraries(bounds)

Fetch library POIs from OSM (amenity=library).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

pharmacies(bounds)

Fetch pharmacy POIs from OSM (amenity=pharmacy).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

gyms(bounds)

Fetch gym POIs from OSM (amenity=gym).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

cinemas(bounds)

Fetch cinema POIs from OSM (amenity=cinema).

Parameters:

Name Type Description Default
bounds

Area to search: a polygon / GeoDataFrame or (min lon, min lat, max lon, max lat).

required

Returns:

Type Description
DataFrame

One row per POI (WKB geometry in EPSG:4326 and its OSM tags).

tag_query(key, value)

Build a POI query function for any OSM tag, e.g. tag_query("amenity", "dentist").

The returned function has the same signature as the named queries above (:func:schools, :func:groceries, ...): query(bounds) -> pl.DataFrame. It searches nodes, ways and relations tagged key=value inside bounds. Use value="*" to match any value of key. Tag reference: https://wiki.openstreetmap.org/wiki/Map_features

Parameters:

Name Type Description Default
key str

OSM tag key, e.g. "amenity".

required
value str

Tag value, or "*" for any value.

required

Returns:

Type Description

A function query(bounds) -> pl.DataFrame.