geohierarchy¶
geohierarchy: hierarchical spatial data management with controlled column propagation.
GeoHierarchy(crs='EPSG:4326', capacity_split=True)
¶
A graph of spatial levels with controlled, direction-aware column propagation.
A :class:GeoHierarchy holds a set of named "levels", each backed by a
geometry (polygons, lines, points, H3 cells, ...) and a table of
attribute columns. Levels are wired into a graph by passing parent
and/or child level names to :meth:add_level. The graph does not
need to be a tree: a level can have several parents and several
children (e.g. two levels can both be a parent of the same child, or
one level can feed into two unrelated hierarchy branches).
Every attribute column that should be shared across levels needs
exactly one :class:~geohierarchy.aggregation.AggregationStrategy,
registered with :meth:set_aggregation (or passed directly to
:meth:add_level). :meth:propagate then walks the graph and fills
in that column everywhere it is missing: values move from a level to
its parents by aggregation ("upscaling") and from a level to its
children by disaggregation ("downscaling"). A level's own native
values -- whether provided at creation or injected later with
:meth:add_vector_data / :meth:add_raster_data -- are never
overwritten by propagated values.
Example
gh = GeoHierarchy() gh.add_level("county", county_gdf, id_col="geoid", agg=Sum()) gh.add_level("tract", tract_gdf, id_col="geoid", agg=Sum(), parent="county") gh.add_vector_data(streets_gdf, level="tract", agg=Mean()) gh.propagate() gh["county"] # GeoDataFrame with columns filled in at every level
Attributes:
| Name | Type | Description |
|---|---|---|
crs |
Common coordinate reference system all level geometries are reprojected to. |
|
levels |
Dict[str, DataFrame]
|
Mapping of level name to its Polars attribute table (geometry excluded). |
geometries |
Dict[str, GeoDataFrame]
|
Mapping of level name to a GeoDataFrame with just the id column, geometry, and geoweighting column. |
id_cols |
Dict[str, str]
|
Mapping of level name to the name of its unique id column. |
geoweight_by |
Dict[str, str]
|
Mapping of level name to whether area or length is used to weight overlaps involving that level. |
parents |
Dict[str, Set[str]]
|
Mapping of level name to the set of its parent level names in the level graph. |
children |
Dict[str, Set[str]]
|
Mapping of level name to the set of its child level names in the level graph. |
columns |
Dict[str, Dict[str, Set[str]]]
|
Mapping of column name to bookkeeping about which levels hold native values, which hold values derived through propagation, and which levels currently have the column at all. |
aggregations |
Dict[str, Dict[str, AggregationStrategy]]
|
Registry of aggregation strategies, keyed by
|
non_propagable_cols |
Set[str]
|
Column names (geometry-derived metadata, id columns, ...) that are always excluded from propagation and can never be re-enabled. |
excluded_columns |
Set[str]
|
Column names that would otherwise be eligible
for propagation but have been opted out with
:meth: |
Initialize an empty hierarchy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crs
|
Any
|
Coordinate reference system (anything accepted by
:class: |
'EPSG:4326'
|
propagation_columns
property
¶
The current set of columns eligible for cross-level propagation.
This is the live "column list" :meth:propagate acts on: every
registered column except geometry metadata/id columns and any
column excluded with :meth:exclude_column.
set_aggregation(column, agg=None, level=None, *, upscale=None, downscale=None, _auto_propagate=True)
¶
Register the aggregation strategy for a column.
Call this with just column to set a column-wide default
strategy, with just level (column=None) to set the default
for every propagatable column native to that level, or with both
to override the strategy for that specific column/level
combination -- which takes precedence over the other two forms
when resolving what to use during propagation.
Changing an existing strategy invalidates any values already
derived from it, and this call triggers :meth:propagate itself
(unless the column doesn't exist at any level yet), so there's no
need to call it manually afterward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
Optional[str]
|
Column name the strategy applies to. May be |
required |
agg
|
Optional[AggregationStrategy]
|
Aggregation strategy instance to register, used for both
upscaling and downscaling. Omit if you pass |
None
|
level
|
Optional[str]
|
Level name the strategy applies to. |
None
|
upscale
|
Optional[AggregationStrategy]
|
Strategy whose upscale (fine -> coarse) behavior is
used. Combine with |
None
|
downscale
|
Optional[AggregationStrategy]
|
Strategy whose downscale (coarse -> fine) behavior
is used, paired with |
None
|
Raises:
| Type | Description |
|---|---|
Exception
|
If neither |
exclude_column(column)
¶
Opt a column out of cross-level propagation.
The column keeps its native values at whatever levels it already
has them (from :meth:add_level, :meth:add_vector_data, or
:meth:add_raster_data), but is dropped from every other level it
had reached through a previous :meth:propagate call, and future
calls to :meth:propagate skip it entirely. No aggregation
strategy is required for an excluded column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
Column name to exclude. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
include_column(column)
¶
Re-enable propagation for a column previously excluded.
Has no effect if column was never excluded. Triggers
:meth:propagate itself, which fills the column in at every
reachable level using whichever aggregation strategy is
registered for it (which must be set separately, e.g. with
:meth:set_aggregation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
Column name to re-enable. |
required |
add_level(name, gdf, id_col=None, agg=None, parent=None, child=None, geoweight_by=None)
¶
Add a spatial level (a hierarchy layer) built from a GeoDataFrame.
The geometry is reprojected to the hierarchy's CRS, and derived
geometry metadata (area, length, bounds, centroid, geometry type)
is computed and stored as non-propagable columns. The remaining
columns become candidate propagation columns and must each resolve
to an aggregation strategy, either supplied here via agg or
registered separately with :meth:set_aggregation.
This triggers :meth:propagate itself, so there's no need to call
it manually afterward. If parent/child connects this level
to levels that already hold propagated (non-native) values, those
values are dropped first and recomputed, since the new edge might
now offer a higher-priority source (a child always outranks a
parent -- see :meth:propagate).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique name for the level. |
required |
gdf
|
GeoDataFrame
|
Source geometries and attributes for the level. |
required |
id_col
|
Optional[str]
|
Name of an existing column in |
None
|
agg
|
Optional[Union[AggregationStrategy, Dict[str, AggregationStrategy]]]
|
Aggregation strategy applied to every propagatable column
in |
None
|
parent
|
Optional[_LevelNames]
|
Name or list of names of this level's parent(s) in the level graph. A level may have any number of parents. |
None
|
child
|
Optional[_LevelNames]
|
Name or list of names of this level's child(ren) in the level graph. A level may have any number of children. |
None
|
geoweight_by
|
Optional[Literal['area', 'length']]
|
Whether to weight spatial overlaps by |
None
|
propagate()
¶
Fill in missing columns across every level of the hierarchy graph.
:meth:add_level, :meth:set_aggregation, :meth:add_vector_data,
:meth:add_raster_data, :meth:exclude_column, and
:meth:include_column all call this automatically after they
change anything that could affect propagation, so it normally
never needs to be called directly. The one exception is mutating
hierarchy.levels[name] in place (e.g. for quick experiments):
that bypasses the column registry entirely, so call
:meth:propagate yourself afterward -- and prefer registering any
new native data through :meth:set_aggregation, :meth:add_level,
or :meth:add_vector_data instead, since a column that has
already been registered once only has its native levels rescanned
the first time, not on every :meth:set_aggregation call.
Every propagatable column is pushed from each level to its parents (aggregation / "upscaling") and pushed from each level to its children (disaggregation / "downscaling"), repeating until no more levels can be filled in. Columns that already hold values at a level (native or previously derived) are left untouched, so calling this repeatedly is idempotent.
The upscale pass always runs to completion before the downscale pass starts, so when a level could receive a column both from a child (via aggregation) and from a parent (via disaggregation), the child's value wins: the level is filled from its child before the downscale pass ever considers filling it from its parent.
Any propagatable column stripped of its level membership (e.g. because its aggregation strategy changed) is dropped from that level's table before propagation resumes.
A column that needs to cross an edge but has no aggregation
strategy registered for the source level is never fatal: it's
skipped (left missing at levels it couldn't reach) and a
UserWarning is emitted pointing at :meth:set_aggregation.
This matters because propagation now runs automatically after
almost every call, so one column missing a strategy should never
block unrelated changes elsewhere in the hierarchy.
add_vector_data(gdf, level, columns=None, agg=None, geoweight_by=None, upscale=None, buffer=0, fill_null=0, intersection_mode=None)
¶
Inject columns from an external (non-layer) vector dataset into a level.
Unlike :meth:add_level, gdf does not become part of the
hierarchy graph -- it is only used as a one-off source of column
values for level. The direction of resampling is auto-detected
(a finer source upscales into level, a coarser source
downscales) unless upscale is given explicitly. The strategy
passed in agg is also registered for the injected columns
going forward, so it is what :meth:propagate later uses to move
them to every other level -- which happens automatically as part
of this call, so there's no need to call :meth:propagate
manually afterward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
External geometries and attributes to inject from. |
required |
level
|
str
|
Name of the level to inject the columns into. |
required |
columns
|
Optional[Union[str, List[str]]]
|
Column name or list of column names in |
None
|
agg
|
Union[AggregationStrategy, Dict[str, AggregationStrategy], None]
|
Aggregation strategy (or per-column mapping) used both for this injection and registered for future propagation of the column. |
None
|
geoweight_by
|
Optional[Literal['area', 'length']]
|
Whether to weight overlaps by |
None
|
upscale
|
Optional[bool]
|
Force the resampling direction. If |
None
|
buffer
|
float
|
Optional buffer distance (in the hierarchy CRS' units) applied to whichever side is polygonal, useful for capturing near-miss overlaps (e.g. streets near block boundaries). |
0
|
fill_null
|
Union[int, float, Dict[str, Union[int, float]], None]
|
Value(s) used to fill nulls left after injection --
a scalar applied to every injected column, a per-column
mapping, or |
0
|
intersection_mode
|
Optional[Literal['centroid', 'touches', 'exact', 'intersects']]
|
Forwarded to :func: |
None
|
Raises:
| Type | Description |
|---|---|
Exception
|
If |
add_raster_data(raster, column, level, agg=None, upscale=True, transform=None, crs=None)
¶
Inject a raster band's values into a level as pixel-centroid points.
The raster is vectorized into point geometries at each pixel
centroid (non-null cells only), then delegated to
:meth:add_vector_data with geoweight_by="area".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster
|
Union[ndarray, str]
|
Either a path to a raster file (opened with
|
required |
column
|
str
|
Name to give the injected column. |
required |
level
|
str
|
Name of the level to inject the column into. |
required |
agg
|
Union[AggregationStrategy, Dict[str, AggregationStrategy], None]
|
Aggregation strategy (or per-column mapping) used for
this injection and registered for future propagation. See
:meth: |
None
|
upscale
|
bool
|
Whether to aggregate pixels into level polygons
( |
True
|
transform
|
Affine transform for |
None
|
|
crs
|
Coordinate reference system for |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
get_level(name, columns=None)
¶
Return a level's geometry joined with its attribute table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the level to retrieve. |
required |
columns
|
Optional[Sequence[str]]
|
If given, only these attribute columns (plus the id
column, always included) are pulled from the level's Polars
attribute table before the pandas merge/ |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A GeoDataFrame combining the level's geometry with the |
GeoDataFrame
|
requested attribute columns (or all of them, if |
GeoDataFrame
|
|
level_bounds(name)
¶
Return a level's (minx, miny, maxx, maxy) extent, without materializing it.
:meth:add_level already stores per-feature minx/miny/
maxx/maxy columns, so the level's extent is four Polars
aggregations over columns already in memory. Callers that only need
an extent (e.g. centering a map) previously went through
:meth:get_level, which re-joins geometry with the full attribute
table row by row -- gigabytes of work for four numbers on a
metro-scale level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the level. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
|
AggregationStrategy(geoweighted=False, mapping='overlap', preserve_total=False, intersection_mode=None)
¶
Bases: ABC
Base class describing how a column resamples between hierarchy levels.
Subclasses implement both directions of resampling: upscale_aggs
combines many fine-grained rows into one coarse row (a Polars group-by
aggregation), while downscale_exprs splits or broadcasts a coarse
row's value across its matching fine-grained rows.
Attributes:
| Name | Type | Description |
|---|---|---|
geoweighted |
If |
|
mapping |
Which id-mapping function pairs source and destination
rows: |
|
preserve_total |
Whether a column using this strategy has a
meaningful total that downscaling must reproduce exactly (an
absolute/additive quantity, e.g. population) as opposed to a
relative one with no sensible total (a rate, ratio, or median,
e.g. income). |
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geoweighted
|
bool
|
Whether to weight rows by geometric overlap fraction during aggregation. |
False
|
mapping
|
str
|
Id-mapping mode, |
'overlap'
|
preserve_total
|
bool
|
Whether this column's downscaled total should exactly match its source total (see class docstring). |
False
|
intersection_mode
|
Optional[str]
|
How source/destination geometries are paired
-- |
None
|
upscale_aggs(columns)
abstractmethod
¶
Build group-by aggregation expressions for fine -> coarse resampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build aggregation expressions for. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column, suitable for use inside |
List[Expr]
|
|
downscale_exprs(columns, group_col)
abstractmethod
¶
Build row-wise expressions for coarse -> fine resampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build expressions for. |
required |
group_col
|
str
|
Name of the column identifying which source (coarse) row each destination row belongs to. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column, suitable for use inside |
List[Expr]
|
|
List[Expr]
|
has no meaningful downscale behavior. |
consolidate_downscale(columns)
¶
Combine multiple downscaled fragments landing on the same destination row.
A destination geometry can overlap more than one source row (e.g. a street crossing two tracts during a tract -> street downscale), which produces one fragment row per source it overlaps. This collapses those fragments -- already grouped by destination id -- back into a single row per destination.
The default keeps an arbitrary single fragment's value, which is
correct for strategies that broadcast the same (or a directly
comparable) value to every fragment. :class:Sum overrides this
to add the fragments instead, since its downscaled shares are
specifically built to sum back to the original total.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to consolidate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column, suitable for use inside |
List[Expr]
|
|
upscale(df, group_col, columns)
¶
Aggregate df from fine to coarse rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Row-level data joined against the destination id mapping. |
required |
group_col
|
str
|
Name of the destination (coarse) id column to group by. |
required |
columns
|
List[str]
|
Column names to aggregate. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per distinct |
DataFrame
|
columns. |
downscale(df, group_col, columns)
¶
Disaggregate df from coarse to fine rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Row-level data joined against the source id mapping. |
required |
group_col
|
str
|
Name of the source (coarse) id column each row belongs to. |
required |
columns
|
List[str]
|
Column names to disaggregate. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Sum(weight_column=None, geoweighted=False, intersection_mode=None)
¶
Bases: AggregationStrategy
Additive quantities such as population or vehicle counts.
Upscaling sums the (optionally weighted) values; downscaling splits a coarse total proportionally across destination rows using the same weights, so totals are preserved in both directions.
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight_column
|
Optional[str]
|
Optional column whose values weight each row's contribution to the sum, on top of any geoweighting. |
None
|
geoweighted
|
bool
|
Whether to additionally weight rows by geometric overlap fraction. |
False
|
intersection_mode
|
Optional[str]
|
|
None
|
upscale_aggs(columns)
¶
Weighted sum of each column (see :func:sum_agg).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to aggregate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
downscale_exprs(columns, group_col)
¶
Proportional share of the coarse total for each row (see :func:divide_expr).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build expressions for. |
required |
group_col
|
str
|
Column identifying the source (coarse) row of each destination row. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column. |
consolidate_downscale(columns)
¶
Add the fragments of a destination row: the shares sum back to the source totals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to consolidate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
Mean(weight_column=None, geoweighted=False, intersection_mode=None)
¶
Bases: AggregationStrategy
Intensive quantities such as rates, incomes, or accessibility scores.
Upscaling computes a (optionally weighted) average; downscaling broadcasts that average back down, weighted the same way, unless the strategy is unweighted (plain average), in which case there is no meaningful per-row split and the value is left for the caller's fallback (typically a plain broadcast join).
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight_column
|
Optional[str]
|
Optional column whose values weight each row in the average, on top of any geoweighting. |
None
|
geoweighted
|
bool
|
Whether to additionally weight rows by geometric overlap fraction. |
False
|
intersection_mode
|
Optional[str]
|
|
None
|
upscale_aggs(columns)
¶
Weighted mean of each column (see :func:mean_agg).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to aggregate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
downscale_exprs(columns, group_col)
¶
The coarse weighted mean broadcast to each row (see :func:mean_expr); empty when the strategy is unweighted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build expressions for. |
required |
group_col
|
str
|
Column identifying the source (coarse) row of each destination row. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column. |
Max(geoweighted=False, mapping='overlap', preserve_total=False, intersection_mode=None)
¶
Bases: AggregationStrategy
Take the maximum value across source rows; has no downscale behavior.
upscale_aggs(columns)
¶
Maximum of each column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to aggregate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
downscale_exprs(columns, group_col)
¶
No downscale for a maximum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build expressions for. |
required |
group_col
|
str
|
Column identifying the source (coarse) row of each destination row. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column (always empty). |
consolidate_downscale(columns)
¶
Maximum of the fragments of a destination row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to consolidate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
Min(geoweighted=False, mapping='overlap', preserve_total=False, intersection_mode=None)
¶
Bases: AggregationStrategy
Take the minimum value across source rows; has no downscale behavior.
upscale_aggs(columns)
¶
Minimum of each column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to aggregate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
downscale_exprs(columns, group_col)
¶
No downscale for a minimum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build expressions for. |
required |
group_col
|
str
|
Column identifying the source (coarse) row of each destination row. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column (always empty). |
consolidate_downscale(columns)
¶
Minimum of the fragments of a destination row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to consolidate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
SmoothMean(k=6, power=2.0, density=False)
¶
Bases: AggregationStrategy
A downscale that blends several nearby source cells instead of copying one.
:class:Mean and :class:Sum's downscale strictly follows the source
geometry's boundaries: every destination row gets a value derived only
from whichever source row(s) it geometrically overlaps, so the result
is blocky wherever the source grid is much coarser than the
destination grid (e.g. downscaling from H3 resolution 8 to 9). This
strategy instead uses :func:geohierarchy.utils.get_knn_mapping to
blend each destination row's value from its k nearest source
centroids, inverse-distance weighted, which smooths out those
boundaries.
Only its downscale behavior is meaningful -- combine it with a normal
upscale strategy via :func:aggregation_strategy, e.g.::
set_aggregation("population", upscale=Sum(), downscale=SmoothMean(k=6, density=True))
:meth:upscale_aggs still works standalone (plain unweighted mean), so
the strategy is usable directly for a column that's only ever
downscaled.
density matters for any additive (count-like) column: a source
cell's raw count isn't comparable across neighbors of different sizes,
and blending raw counts directly to a much smaller destination cell
(as with H3 resolution 8 -> 9, where each finer cell is ~1/7 the area)
would hand it a value sized for the source's area, inflating its
.density several-fold. With density=True, each neighbor's value
is divided by that neighbor's own area before blending, and the
blended density is scaled back up by the destination row's own
(smaller) area, so counts stay proportionate to cell size. Leave it
False for columns that are already an intensive quantity (medians,
rates, per-capita figures), which don't need this conversion.
Warning
Only verified for the downscale direction (its intended use). If a
column combining this strategy is ever upscaled through the same
edge, the id-mapping mode this strategy selects ("knn")
currently applies uniformly to both directions, which has not been
validated against upscale_aggs's expectations.
Attributes:
| Name | Type | Description |
|---|---|---|
k |
Number of nearest source neighbors blended per destination row. |
|
power |
Inverse-distance weighting exponent. |
|
density |
Whether to blend in per-area density space, converting back to a magnitude sized for the destination row afterward. |
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of nearest source neighbors to blend. |
6
|
power
|
float
|
Inverse-distance weighting exponent; higher values concentrate more weight on the nearest neighbor(s). |
2.0
|
density
|
bool
|
Whether |
False
|
upscale_aggs(columns)
¶
Plain unweighted mean of each column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to aggregate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
downscale_exprs(columns, group_col)
¶
Nothing per row: the blend happens in :meth:consolidate_downscale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to build expressions for. |
required |
group_col
|
str
|
Column identifying the source (coarse) row of each destination row. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars expression per column (always empty). |
consolidate_downscale(columns)
¶
Inverse-distance blend of the k nearest source values (in density space if density); null when every neighbour is null.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
List[str]
|
Column names to consolidate. |
required |
Returns:
| Type | Description |
|---|---|
List[Expr]
|
One Polars aggregation expression per column. |
ColumnNotFoundError
¶
Bases: Exception
Raised when a requested column does not exist in the dataset.
AggregationStrategyError
¶
Bases: Exception
Raised when an aggregation strategy is configured incorrectly.
aggregation_strategy(upscale, downscale=None)
¶
Combine one strategy's upscale behavior with another's downscale behavior.
Useful when the natural way to aggregate a column upward (e.g. a weighted sum) differs from how it should be split back downward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upscale
|
AggregationStrategy
|
Strategy whose |
required |
downscale
|
Optional[AggregationStrategy]
|
Strategy whose |
None
|
Returns:
| Type | Description |
|---|---|
AggregationStrategy
|
A copy of |
AggregationStrategy
|
|
h3_cells(geometry, resolution)
¶
Build an H3 cell grid covering a geometry, as polygon cells.
Useful for building an H3 hierarchy level with :meth:GeoHierarchy.add_level
-- H3 cells are plain polygons once vectorized, so they work as a core
layer exactly like any other polygon geometry (they can also be used
with :meth:GeoHierarchy.add_vector_data / :meth:GeoHierarchy.add_raster_data
as non-layer source data).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
GeoDataFrame | GeoSeries
|
Geometries whose combined extent the H3 grid should cover. Reprojected to EPSG:4326 first, since H3 operates on geographic coordinates. |
required |
resolution
|
int
|
H3 resolution (0 = coarsest, ~15 = finest). See the H3 documentation for the approximate cell size at each level. |
required |
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A GeoDataFrame in EPSG:4326 with an |
GeoDataFrame
|
index as a hex string) and one polygon per covering cell. |
get_knn_mapping(src_gdf, dst_gdf, src_id, dst_id, k=6, power=2.0)
¶
Build an inverse-distance-weighted k-nearest-neighbor mapping, for smoothed downscaling.
Unlike :func:get_id_mapping (which only pairs geometries that
physically overlap, reproducing the source geometry's boundaries
exactly), this pairs every src_gdf centroid with its k nearest
dst_gdf centroids, weighted by inverse distance and normalized to
sum to 1 within each src_id group. Used by
:class:~geohierarchy.aggregation.SmoothMean so a downscaled value
blends across several source cells instead of copying whichever one
happens to contain (or nearly contain) a given destination cell,
smoothing out the source geometry's hard boundaries.
Also computes each row's polygon area (reusing an existing "area"
column if either GeoDataFrame already has one -- e.g. the "area"
column :class:~geohierarchy.core.GeoHierarchy stores on every level's
geometry table -- rather than recomputing it) and carries it along as
"_query_area" (area of the src_gdf row each mapping row is
computed for) and "_neighbor_area" (area of the paired
dst_gdf neighbor). :class:~geohierarchy.aggregation.SmoothMean
uses these to convert an additive count to a density (dividing by
whichever side the value's own row is on) before blending, and back to
a count sized for the row being computed afterward. Meaningless (and
unused) for non-polygon geometries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_gdf
|
GeoDataFrame
|
Rows to compute neighbor weights for (the finer, "destination-of-propagation" geometries in a downscale). |
required |
dst_gdf
|
GeoDataFrame
|
Candidate neighbor geometries (the coarser, "source-of-propagation" geometries in a downscale). |
required |
src_id
|
str
|
Id column in |
required |
dst_id
|
str
|
Id column in |
required |
k
|
int
|
Number of nearest |
6
|
power
|
float
|
Inverse-distance weighting exponent; higher values concentrate more weight on the nearest neighbor(s). |
2.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with ``[src_id, dst_id, "_geoweight", "_query_area", |
DataFrame
|
"_neighbor_area"] |
get_id_mapping(src_gdf, dst_gdf, src_id, dst_id, geoweighted=False, how=None, intersection_mode=None)
¶
Creates a mapping table between two geometry levels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_gdf
|
GeoDataFrame
|
Source geometry (finer). |
required |
dst_gdf
|
GeoDataFrame
|
Destination geometry (coarser). |
required |
src_id
|
str
|
ID column in source layer. |
required |
dst_id
|
str
|
ID column in destination layer. |
required |
geoweighted
|
bool
|
Legacy flag, kept for backward compatibility.
Ignored whenever |
False
|
how
|
Optional[Literal['area', 'length']]
|
|
None
|
intersection_mode
|
Optional[Literal['centroid', 'touches', 'exact', 'intersects']]
|
How
If |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Mapping table with [src_id, dst_id, geoweight]. |
edges_to_level(edges_gdf, level_gdf, id_col, columns, agg=None, geometry_col='geometry', crs=None)
¶
Aggregate columns from a line-geometry GeoDataFrame onto a polygon level.
Builds a single-level :class:~geohierarchy.core.GeoHierarchy from
level_gdf, injects edges_gdf's attribute columns into it with
:meth:~geohierarchy.core.GeoHierarchy.add_vector_data (length-weighted,
since edges_gdf holds line geometries), and returns the resulting
polygon layer with just the requested columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges_gdf
|
GeoDataFrame
|
Source GeoDataFrame of line geometries (e.g. street network edges) carrying the attribute columns to aggregate. |
required |
level_gdf
|
GeoDataFrame
|
Target polygon GeoDataFrame to aggregate onto -- an H3
grid from :func: |
required |
id_col
|
str
|
Name of the unique id column in |
required |
columns
|
Union[str, List[str]]
|
Column name or list of column names in |
required |
agg
|
Union[AggregationStrategy, Dict[str, AggregationStrategy], None]
|
Aggregation strategy applied to every column in |
None
|
geometry_col
|
str
|
Name of the geometry column in |
'geometry'
|
crs
|
Coordinate reference system the hierarchy (and the returned
GeoDataFrame) should use. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
A copy of |
GeoDataFrame
|
geometry, and the aggregated |
edges_to_h3_by_distance(edges_gdf, h3_cells, columns, resolution, margin_m=10.0, agg=None, fallback_radius_multiplier=5.0)
¶
Aggregate line-geometry columns onto H3 cells by centroid distance, not geometric overlap.
An alternative to :func:edges_to_level for H3 targets specifically:
instead of a GEOS polygon/line overlay (which can be expensive or even
memory-unstable for very large edge counts -- e.g. shapely.union_all
over 800K+ street edges failing outright with GEOSException:
std::bad_alloc), "touching" is defined purely by distance -- an H3
cell counts as touched by a line if any point on that line falls
within margin_m of the cell's centroid, checked via a
scipy.spatial.cKDTree radius query against densified line-sample
points (see :func:_densify_lines). No Shapely geometry object is
built anywhere in this path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges_gdf
|
GeoDataFrame
|
Source GeoDataFrame of line geometries carrying the attribute columns to aggregate. |
required |
h3_cells
|
Sequence[str]
|
Candidate H3 cells to test (e.g. every cell with population, to skip cells irrelevant to the caller). |
required |
columns
|
Union[str, List[str]]
|
Column name or list of column names in |
required |
resolution
|
int
|
H3 resolution of |
required |
margin_m
|
float
|
Extra distance beyond one cell diameter still counted as "touching". |
10.0
|
agg
|
Union[AggregationStrategy, Dict[str, AggregationStrategy], None]
|
Aggregation strategy applied to every column, or a per-column
mapping. Defaults to :class: |
None
|
fallback_radius_multiplier
|
Optional[float]
|
Guarantees every cell in |
5.0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
cell within |
DataFrame
|
nearby edge are simply absent. |
raster_to_polygons(raster_array, transform, raster_crs, polygons, id_col, nodata=None)
¶
Area-weighted, mass-conserving resample of a raster onto a polygon tiling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_array
|
ndarray
|
2D array of pixel values (e.g. one band read from a
GeoTIFF). NaN and |
required |
transform
|
Affine
|
Affine transform mapping pixel (col, row) -> raster CRS
coordinates (as returned by |
required |
raster_crs
|
CRS of |
required | |
polygons
|
GeoDataFrame
|
Target polygon tiling (e.g. H3 cells from
:func: |
required |
id_col
|
str
|
Name of the unique identifier column in |
required |
nodata
|
Optional[float]
|
Sentinel value in |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with columns |
DataFrame
|
polygon touched by at least one valid pixel, with a value equal to |
DataFrame
|
the area-weighted sum of that pixel's contributions. Guarantees (1) |
DataFrame
|
every touching polygon appears, (2) |
DataFrame
|
|
DataFrame
|
combined extent, and (3) each polygon's implied density |
DataFrame
|
( |
DataFrame
|
the min, of the densities of the pixels it touches. See the module |
DataFrame
|
docstring for the algorithm and why those hold by construction. |
raster_to_h3(raster_array, transform, raster_crs, resolution, value_col='value', h3_col='h3_cell', nodata=None)
¶
Convenience wrapper: area-weighted, mass-conserving raster -> H3 grid resample.
Builds an H3 cell grid covering the raster's own extent at resolution
(via :func:~geohierarchy.utils.h3_cells) and delegates to
:func:raster_to_polygons. This is the generic primitive
pycensus's WorldPop loader applies with WorldPop-specific knowledge
(nodata handling, AOI cropping, CRS choice) layered on top -- see
pycensus.census.worldwide.worldpop.loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_array
|
ndarray
|
2D array of pixel values. |
required |
transform
|
Affine
|
Affine transform for |
required |
raster_crs
|
CRS of |
required | |
resolution
|
int
|
H3 resolution for the output grid. |
required |
value_col
|
str
|
Name to give the output value column. |
'value'
|
h3_col
|
str
|
Name to give the output H3 cell-id column. |
'h3_cell'
|
nodata
|
Optional[float]
|
Sentinel value in |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with |
DataFrame
|
H3 cell touched by at least one valid pixel. |
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). |
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. |