geohierarchy.spatial_cache¶
Cache expensive spatial CORRESPONDENCE (id <-> id / id <-> pixel) computations.
Every function here answers "which unit maps to which other unit" and
persists that answer as a parquet file, deliberately separate from any
data VALUES. The idea: correspondences depend only on GEOMETRY (raster grid,
H3 resolution, polygon boundaries, street network), not on whatever attribute
is currently being aggregated through them. When only the values change --
a new WorldPop release, a re-scored access_score, a re-run with different
aggregation parameters -- but the underlying geometries are unchanged, the
expensive spatial join/rule should not have to run again: this module lets
callers look up the cached correspondence and redo only the (fast) value
re-aggregation.
Each mapping is its own parquet file, named so the two id-spaces it connects and the geometry version it was computed against are both legible from the filename (and re-checked against a stored geometry-fingerprint on load, so a mapping is never silently reused for a geometry it wasn't built from).
Nothing in this module is wired into any production pipeline. It is meant to be adopted deliberately, one call site at a time, once verified.
raster_grid_key(transform, shape, resolution)
¶
Content-based cache key for a raster grid + target H3 resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform
|
|
required | |
shape
|
Sequence[int]
|
|
required |
resolution
|
int
|
Target H3 resolution the mapping was/will be built for. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A short, deterministic hex string. Two rasters with the same grid |
str
|
(affine + shape) and the same target resolution always produce the |
str
|
same key; anything different produces a different one. |
geometry_version_key(gdf, id_col)
¶
Content-based fingerprint for a polygon/line layer's geometry (not its attributes).
Used to detect staleness: a cache built against one version of a boundary layer (e.g. census tracts) must not be silently reused once the boundaries themselves change (a new TIGER/Line vintage, a re-clipped AOI, ...). Cheap by design -- total bounds, feature count, and a hash of the id column and per-feature bounds -- rather than a hash of full WKB, since this only needs to change when the geometry actually changes, not be cryptographically unforgeable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Geometry layer to fingerprint. |
required |
id_col
|
str
|
Name of the layer's unique id column. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A short, deterministic hex string. |
load_mapping(cache_dir, name, key)
¶
Load a previously cached mapping table, if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
Union[str, Path]
|
Directory mappings are cached under. |
required |
name
|
str
|
Logical mapping name (e.g. |
required |
key
|
str
|
Content-based cache key identifying the exact geometry inputs. |
required |
Returns:
| Type | Description |
|---|---|
Optional[DataFrame]
|
The cached mapping as a Polars DataFrame, or |
Optional[DataFrame]
|
entry exists for this |
save_mapping(mapping, cache_dir, name, key)
¶
Persist a mapping table to its cache slot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
DataFrame
|
Mapping table to persist. |
required |
cache_dir
|
Union[str, Path]
|
Directory mappings are cached under. |
required |
name
|
str
|
Logical mapping name (e.g. |
required |
key
|
str
|
Content-based cache key identifying the exact geometry inputs. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path the mapping was written to. |
build_raster_h3_mapping(h3_cells, transform, shape, resolution, cache_dir, raster_crs=None, name='h3_to_raster_pixel', force=False)
¶
Compute (or load a cached) closed-form mapping of H3 cells to raster pixel row/col.
Raster pixels have no natural id, so unlike the id-correspondence
mappings in this module, this one is a rule: for each H3 cell,
compute its centroid with :func:_h3_cell_centroids (H3-native, no
Shapely) and invert the raster's affine transform to find which pixel
column/row that centroid falls into -- pure arithmetic, no geometry
objects, no per-row Python loop.
This is only a sound approximation when pixel size and H3 cell size at
resolution are comparable and the study area is small enough that
pixel curvature/distortion don't make a fixed affine rule meaningfully
wrong (true at every resolution this codebase currently uses -- see
:func:UrbanAccessAnalyzer.h3_ops.from_raster_centroid, which performs
the equivalent per-pixel-centroid assignment in the other direction and
resolution-matches to keep the same error bounded). Callers with pixels
much coarser or finer than the target H3 resolution should pick
resolution accordingly (see :func:apply_raster_h3_mapping's
population-conservation note) rather than relying on this rule alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h3_cells
|
Sequence[str]
|
H3 cell index strings covering the raster's extent (e.g.
from :func: |
required |
transform
|
Raster's affine transform ( |
required | |
shape
|
Sequence[int]
|
|
required |
resolution
|
int
|
H3 resolution of |
required |
cache_dir
|
Union[str, Path]
|
Directory the mapping is cached under. |
required |
raster_crs
|
CRS the raster (and |
None
|
|
name
|
str
|
Cache artifact name. |
'h3_to_raster_pixel'
|
force
|
bool
|
Recompute even if a cache entry already exists. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
one row per H3 cell whose centroid falls inside the raster's |
DataFrame
|
extent (out-of-extent cells are dropped). |
apply_raster_h3_mapping(mapping, array, resolution, target_resolution=None, value_col='value')
¶
Apply a cached raster<->H3 mapping to a pixel array, gathering values by fast indexing.
Preserves the same population-conservation guarantee as
:func:UrbanAccessAnalyzer.h3_ops.from_raster_centroid: every pixel's
value is assigned whole to exactly one H3 cell at resolution (a
centroid-based, not area-weighted, assignment -- same trade-off the
existing direct computation makes), so sum(value) over the returned
table equals sum(array) restricted to pixels whose centroid maps to
an in-mapping H3 cell. Many-to-one (several H3 cells -> one pixel, when
the pixel is coarser than the H3 grid) is handled naturally since every
such cell independently reads the same pixel value -- callers wanting
an exact partition of that pixel's total across those cells (rather
than each cell getting the full pixel value / density-preserving
behavior) should assign at the resolution :func:build_raster_h3_mapping
was built for, then aggregate up via H3's exact parent/child index
nesting (target_resolution, summed) exactly as from_raster_centroid
does via its own resample(..., method="sum") step -- summing nests
exactly across resolutions with no further approximation, so the total
is identical whether cells are assigned directly at a coarse resolution
or via a fine intermediate step summed upward; only per-cell density
accuracy differs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
DataFrame
|
Cached mapping from :func: |
required |
array
|
ndarray
|
2D raster array the mapping's pixel coordinates index into. |
required |
resolution
|
int
|
H3 resolution |
required |
target_resolution
|
Optional[int]
|
If given and different from |
None
|
value_col
|
str
|
Name to give the gathered value column. |
'value'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
build_h3_to_polygon_mapping(h3_gdf, polygon_gdf, h3_id, polygon_id, cache_dir, name='h3_to_census', force=False)
¶
Cache which polygon (e.g. census unit) each H3 cell's centroid falls within.
Polygon boundaries are irregular, so -- unlike the raster case -- this
needs a real point-in-polygon test rather than a closed-form rule;
it wraps :func:~geohierarchy.utils.get_id_mapping (the same
correct, already-used centroid-in-polygon join the rest of
geohierarchy relies on) and adds a caching layer keyed on both
layers' geometry versions, so the join itself only runs once per
(h3 grid, polygon layer) combination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h3_gdf
|
GeoDataFrame
|
H3 cell layer (polygons), e.g. from
:func: |
required |
polygon_gdf
|
GeoDataFrame
|
Target polygon layer (e.g. census tracts). |
required |
h3_id
|
str
|
Id column in |
required |
polygon_id
|
str
|
Id column in |
required |
cache_dir
|
Union[str, Path]
|
Directory the mapping is cached under. |
required |
name
|
str
|
Cache artifact name. |
'h3_to_census'
|
force
|
bool
|
Recompute even if a cache entry already exists. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
names preserved) and |
DataFrame
|
polygon per H3 cell, centroid assignment). |
build_street_to_h3_mapping(edges_gdf, h3_cells, resolution, edge_id, cache_dir, margin_m=10.0, name='street_to_h3', force=False)
¶
Cache which H3 cell(s) each street edge is near, via the existing distance-based join.
Wraps :func:~geohierarchy.edges.edges_to_h3_by_distance's matching
logic (line-densify + KD-tree radius query against H3 centroids) --
the correct, already-used street<->H3 correspondence -- but caches the
resulting (edge_id, h3_cell) pairs themselves rather than any
aggregated value, so re-running with a different attribute column or
aggregation strategy skips the KD-tree query entirely as long as the
edges and H3 grid haven't changed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges_gdf
|
GeoDataFrame
|
Street network edges. Must contain |
required |
h3_cells
|
Sequence[str]
|
Candidate H3 cells (e.g. every cell with population). |
required |
resolution
|
int
|
H3 resolution of |
required |
edge_id
|
str
|
Id column in |
required |
cache_dir
|
Union[str, Path]
|
Directory the mapping is cached under. |
required |
margin_m
|
float
|
Extra distance beyond one cell diameter still counted as
"touching" -- see :func: |
10.0
|
name
|
str
|
Cache artifact name. |
'street_to_h3'
|
force
|
bool
|
Recompute even if a cache entry already exists. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
(edge, nearby cell) pair. |
compose_street_to_polygon_mapping(street_to_h3, h3_to_polygon, edge_id, h3_id, polygon_id)
¶
Compose a street-to-polygon (e.g. street-to-census) mapping from two cached mappings.
No new spatial computation: a street edge's polygon correspondence is derived purely by joining its already-cached street->H3 correspondence to the already-cached H3->polygon correspondence, on the shared H3 cell id. Keeping this as a composition (rather than its own spatial join) means it's always consistent with the two mappings it's built from and never needs its own cache invalidation logic beyond theirs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
street_to_h3
|
DataFrame
|
Mapping from :func: |
required |
h3_to_polygon
|
DataFrame
|
Mapping from :func: |
required |
edge_id
|
str
|
Id column name shared with |
required |
h3_id
|
str
|
H3 cell id column name shared by both inputs. |
required |
polygon_id
|
str
|
Id column name shared with |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
(edge, polygon) pair reachable through a shared H3 cell. |
build_census_level_mapping(fine_gdf, coarse_gdf, fine_id, coarse_id, cache_dir, name='census_level_mapping', force=False)
¶
Cache a census-level-to-census-level id correspondence (e.g. blockgroup -> tract).
A thin cached wrapper around :func:~geohierarchy.utils.get_id_mapping
(centroid-in-polygon, matching how GeoHierarchy itself resolves
parent/child correspondences), for the common case where the finer
level nests exactly inside the coarser one (blockgroup -> tract ->
county, the hierarchy code/pipeline.py's MAP_CENSUS_LEVELS
already uses).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fine_gdf
|
GeoDataFrame
|
Finer census level (e.g. block groups). |
required |
coarse_gdf
|
GeoDataFrame
|
Coarser census level (e.g. tracts). |
required |
fine_id
|
str
|
Id column in |
required |
coarse_id
|
str
|
Id column in |
required |
cache_dir
|
Union[str, Path]
|
Directory the mapping is cached under. |
required |
name
|
str
|
Cache artifact name. |
'census_level_mapping'
|
force
|
bool
|
Recompute even if a cache entry already exists. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
names preserved). |