Skip to content

geohierarchy.aggregation

Aggregation strategies for hierarchical spatial resampling.

Rules: - NaN → null - null values ignored everywhere - geoweight column is ALWAYS "_geoweight" - IMPORTANT: if all values are null → result is null (NOT 0) - IMPORTANT: weighted ops drop rows where value OR weight are null

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 True, row contributions are additionally weighted by the fraction of geometric overlap (area or length) between the source and destination geometries, using the "_geoweight" column produced by :func:geohierarchy.utils.get_id_mapping.

mapping

Which id-mapping function pairs source and destination rows: "overlap" (:func:geohierarchy.utils.get_id_mapping, geometric intersection) or "knn" (:func:geohierarchy.utils.get_knn_mapping, inverse-distance nearest neighbors -- see :class:SmoothMean).

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). True for :class:Sum. Strategies whose downscale isn't already exactly total-preserving by construction (currently just :class:SmoothMean, whose blending is spatial rather than proportional) use this flag to trigger a corrective rescale in :meth:GeoHierarchy._aggregate_edge_batch -- see :meth:SmoothMean.__init__.

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" or "knn".

'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 -- "centroid", "touches", or "exact" (see :func:geohierarchy.utils.get_id_mapping). None (the default) falls back to legacy behavior derived from geoweighted (True -> "exact", False -> "centroid").

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]

DataFrame.group_by(...).agg(...).

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]

DataFrame.with_columns(...). May be empty if the strategy

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]

DataFrame.group_by(dst_id).agg(...).

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 group_col value with the aggregated

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

df with the disaggregated columns added or replaced.

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]

"centroid", "touches", or "exact" -- see :class:AggregationStrategy.

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]

"centroid", "touches", or "exact" -- see :class:AggregationStrategy.

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.

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 columns hold additive counts that should be blended as densities (see class docstring) rather than blended as-is.

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.

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.

sum_agg(column_name, weight_column=None, geoweighted=False)

Group-by expression for a (weighted) sum: sum(value * weight) over the valid rows.

Rows whose value (or weight) is null or NaN are ignored; a group with no valid row gives null, not 0.

Parameters:

Name Type Description Default
column_name

Column to aggregate.

required
weight_column

Optional column whose values weight each row.

None
geoweighted

Whether to also weight each row by its geometric overlap fraction (the "_geoweight" column).

False

Returns:

Type Description

A Polars aggregation expression named column_name.

sum_expr(column_name, group_col, weight_column=None, geoweighted=False)

Window version of :func:sum_agg: the group's (weighted) sum broadcast to each of its rows.

Parameters:

Name Type Description Default
column_name

Column to aggregate.

required
weight_column

Optional column whose values weight each row.

None
geoweighted

Whether to also weight each row by its geometric overlap fraction (the "_geoweight" column).

False
group_col

Column identifying the group of each row.

required

Returns:

Type Description

A Polars expression named column_name.

mean_agg(column_name, weight_column=None, geoweighted=False)

Group-by expression for a (weighted) mean: sum(value * weight) / sum(weight) over the valid rows.

Parameters:

Name Type Description Default
column_name

Column to aggregate.

required
weight_column

Optional column whose values weight each row.

None
geoweighted

Whether to also weight each row by its geometric overlap fraction (the "_geoweight" column).

False

Returns:

Type Description

A Polars aggregation expression named column_name (null when no row is valid).

mean_expr(column_name, group_col, weight_column=None, geoweighted=False)

Window version of :func:mean_agg: the group's (weighted) mean broadcast to each of its rows.

Parameters:

Name Type Description Default
column_name

Column to aggregate.

required
weight_column

Optional column whose values weight each row.

None
geoweighted

Whether to also weight each row by its geometric overlap fraction (the "_geoweight" column).

False
group_col

Column identifying the group of each row.

required

Returns:

Type Description

A Polars expression named column_name.

divide_expr(column_name, group_col, weight_column=None, geoweighted=False)

Split a group's total across its rows in proportion to their weights: value * weight / sum(weight).

Used to downscale additive columns: the shares of a group add back up to its total.

Parameters:

Name Type Description Default
column_name

Column to aggregate.

required
weight_column

Optional column whose values weight each row.

None
geoweighted

Whether to also weight each row by its geometric overlap fraction (the "_geoweight" column).

False
group_col

Column identifying the source (coarse) row each destination row belongs to.

required

Returns:

Type Description

A Polars expression named column_name (null when the group's weights sum to 0).

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 upscale_aggs is used as-is.

required
downscale Optional[AggregationStrategy]

Strategy whose downscale_exprs is grafted onto a copy of upscale. If None, upscale's own downscale_exprs is kept.

None

Returns:

Type Description
AggregationStrategy

A copy of upscale with downscale_exprs replaced by

AggregationStrategy

downscale's implementation, if provided.