make_weights

make_weights(
    gdf,
    *,
    method='queen',
    k=6,
    threshold=None,
    power=1.0,
    row_standardize=True,
    attach_islands=True,
    entity=None,
    crs='auto',
)

Build a spatial weights matrix from geometry with the library’s conventions.

The weights are keyed by the gdf’s entity ids (so results are auditable by unit), contiguity islands are attached to their nearest neighbor, rows are standardized to sum to one, and a machine- and human-readable description is stored on w.geometrics_meta (spec is the one-liner every spatial result records as w_spec).

Parameters

Name Type Description Default
gdf gpd.GeoDataFrame Geometry frame (see :func:geometrics.read_gdf); its entity column supplies the weight ids. required
method str "queen" / "rook" (shared-boundary contiguity), "knn" (k-nearest-neighbor centroids), "distance_band" (binary within a radius) or "inverse_distance" (:math:1/d^{p} within a radius). 'queen'
k int Number of neighbors for method="knn". 6
threshold float | None Radius for the distance-based methods. None uses the smallest distance that leaves no unit isolated (min_threshold_distance). None
power float Distance-decay exponent :math:p for method="inverse_distance". 1.0
row_standardize bool Standardize each row of W to sum to one (the convention for spatial lags). True
attach_islands bool For contiguity methods, connect units with no shared-boundary neighbor to their nearest neighbor (a :class:~geometrics.GeometricsWarning names them). True
entity str | None Entity id column of gdf; resolved automatically when None. None
crs Any CRS handling for centroid distances (knn / distance methods): "auto" projects to an estimated UTM CRS, None keeps the raw coordinates (reproducing lat/lon-centroid k-NN analyses), anything else is passed to to_crs. 'auto'

Returns

Name Type Description
libpysal.weights.W The weights, with w.geometrics_meta recording method, k, threshold, power, crs, islands_attached, row_standardized, n and the human-readable spec.

Raises

Name Type Description
ValueError For an unknown method, duplicate entity ids, or an out-of-range k.

Examples

Queen contiguity on a two-cell map (each cell has one neighbor):

import geopandas as gpd
from shapely.geometry import box

from geometrics.weights import make_weights

gdf = gpd.GeoDataFrame(
    {"region": ["A", "B"]},
    geometry=[box(0, 0, 1, 1), box(1, 0, 2, 1)],
    crs="EPSG:4326",
)
w = make_weights(gdf, method="queen")
(w.neighbors["A"], w.geometrics_meta["spec"])