geohierarchy.core¶
GeoHierarchy: hierarchical spatial data management with controlled column propagation.
Key rules
- Geometry/meta columns are never propagated across levels.
- Only user-defined attribute columns propagate.
- Every propagating column must resolve to exactly one aggregation strategy for the level it propagates from.
- A level's native (user-provided) non-null values are never
overwritten by propagation. Null native values are the one
exception: they are backfilled from a parent level (downscaled),
since a null means "no value collected here", not "a real value
of nothing" -- see :meth:
GeoHierarchy._fill_native_nulls.
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
|
|