Skip to content

Geo / OSM

The geo package brings real building layouts into the generators: it queries building outlines from OpenStreetMap through the Overpass API (data © OpenStreetMap contributors, ODbL), projects them from WGS84 into a local east-north frame in metres, and hands them to the generators as BuildingFootprint objects (through OsmBuildingPlacement in TnNetworkGenerator, or LvNetworkLayout.from_osm). Design and reasoning: ADR-0011.

The active functions need the optional geo extra (pip install "groundfield[geo]": requests, pyproj, shapely); without it they raise an ImportError with the install command. The data class BuildingFootprint has no optional dependency.

Mathematical and physical context

The geo layer is topological: it decides which buildings exist, where they are and how their foundation earths are oriented. Three effects depend on that geometry rather than on the number of houses: the spreading resistance of a foundation earth grows with its buried length (the perimeter of the outline), the inductive coupling of a foundation to a PEN cable along the street depends on its orientation, and the mutual resistance between the earths depends on the real spacing of the houses, which a regular grid does not reproduce.

Projection. Azimuthal equidistant projection (+proj=aeqd) centred on a user-supplied origin: one tangent plane, distortion below \(10^{-5}\) within about 5 km of the origin, no UTM zone bookkeeping. The origin is never inferred from the data, so two queries of the same area at different dates give identical coordinates.

Foundation outline. A foundation earth (DIN 18014) is a closed conductor in the strip foundation. The generators reduce an outline either to its oriented minimum bounding rectangle (OMBR, the default: smallest rectangle containing the polygon, rotating calipers) or follow the polygon itself (foundation_outline="polygon" of the layout builder). An outline whose OMBR is narrower than 1 m (a mapped wall or fence) is widened to MIN_FOUNDATION_SIDE_M with a warning in both cases; a polygon foundation then follows the widened OMBR.

Requests. Overpass queries are bounded (radius, timeout, response size), validated before they are cached, and retried with back-off; a malformed answer raises OverpassError and is not cached. Every building=* value is a footprint by default; exclude_building_tags (for example NON_SERVICE_BUILDING_TAGS: garages, sheds, carports, …) drops buildings without a service connection.

Example (offline)

import math

import groundfield as gf

# a 12 m x 9 m house turned by 30 degrees, in local metres (east, north)
angle = math.radians(30.0)
corners = [(0.0, 0.0), (12.0, 0.0), (12.0, 9.0), (0.0, 9.0)]
outline = [
    (math.cos(angle) * x - math.sin(angle) * y, math.sin(angle) * x + math.cos(angle) * y)
    for x, y in corners
]
house = gf.BuildingFootprint(polygon_xy_m=outline, osm_id=1)

centre, size, orientation_deg = house.oriented_bounding_rectangle()   # needs the geo extra
assert abs(house.area_m2() - 108.0) < 1e-9
assert abs(size[0] - 12.0) < 1e-9 and abs(size[1] - 9.0) < 1e-9
assert abs(orientation_deg - 30.0) < 1e-9

The tutorial on TN networks (T06) builds a complete network from a stored Overpass answer, without network access; the how-to guide on OSM offline use shows how to cache and replay queries.

API reference

geo

Georeferenced data ingest for groundfield.

This subpackage bridges the external GIS world (OpenStreetMap via the Overpass API, in the future also image-based footprint recognition) and the groundfield.generators stack. The end product is a list of BuildingFootprint instances in a local ENU frame, which a OsmBuildingPlacement then feeds into a TnNetworkGenerator so that synthetic worlds inherit real street layouts and real building outlines for the foundation electrodes.

Optional dependencies

groundfield.geo.osm and groundfield.geo.projection import requests, pyproj, and shapely. These ship in the geo Poetry / pip extra and are not part of the core groundfield install. Calling any of the public APIs without the extra raises a clear ImportError with the install hint::

pip install groundfield[geo]
poetry install --extras geo

The Pydantic data class BuildingFootprint does not depend on any of the optional libraries; it can be imported and serialised on a core install. Only the active operations (querying Overpass, projecting WGS84 to ENU, computing oriented bounding rectangles) need the extra.

Design rationale

See docs/adr/0011-osm-building-footprints.md for the full decision record (subpackage layout, projection choice, caching strategy, integration with the generator stack, deferred Phase B for non-rectangular foundations).

DEFAULT_ENDPOINT module-attribute

DEFAULT_ENDPOINT = 'https://overpass-api.de/api/interpreter'

Default Overpass endpoint. Override with endpoint=….

DEFAULT_MAX_RESPONSE_BYTES module-attribute

DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024

Default cap on the size of an Overpass response (16 MiB).

The cap bounds the memory of decoding the body as well: parsed JSON takes about 6 times its size for building payloads and up to 25 times for a hostile body of empty objects (measured with tracemalloc), i.e. at most about 0.4 GiB. The largest payload of the AP1 catalogue (196 LV networks) is 3 MiB; pass a larger max_response_bytes for wide areas. Until the first 2026.11 consolidation the default was 64 MiB (up to 1.6 GiB parsed, audit L7).

MAX_PAYLOAD_DEPTH module-attribute

MAX_PAYLOAD_DEPTH = 16

Deepest container nesting accepted in an Overpass payload.

An Overpass result nests at most seven levels (payload → elements → element → members → member → geometry → vertex). A body nested far deeper is not an Overpass result: up to about 10 000 levels it decodes and would reach the recursive pure-Python encoder of json.dump() in the cache write (RecursionError beyond about 1 000 levels, audit A2G-05); beyond that the decoder of Python 3.12 / 3.13 raises RecursionError; Python 3.14, whose recursion guard follows the C stack, may decode 100 000 levels (3.14.10 on the CI runner did, 3.14.6 did not). Every case becomes OverpassError right after decoding.

MAX_RADIUS_M module-attribute

MAX_RADIUS_M = 10000.0

Largest accepted search radius in m (one LV / MV network area).

MAX_RETRIES module-attribute

MAX_RETRIES = 5

Largest accepted max_retries.

MAX_RETRY_DELAY_S module-attribute

MAX_RETRY_DELAY_S = 60.0

Longest wait in s between two retries (also caps Retry-After).

MAX_TIMEOUT_S module-attribute

MAX_TIMEOUT_S = 900

Largest accepted timeout_s in s.

MIN_OUTLINE_WIDTH_M module-attribute

MIN_OUTLINE_WIDTH_M = 0.001

Mean width in m below which an outline encloses no area.

The mean width \(w = 2A/P\) of a ring (twice its area over its perimeter, mean_width()) is the width of a long thin rectangle and 0 for identical or collinear vertices. An outline narrower than 1 mm on average is a digitising artefact, not a building: groundfield.geo.osm.parse_overpass_payload() skips it (BuildingFootprint.is_degenerate()). A mapped wall of 5 mm is kept (\(w \approx 5\) mm); generators widen its foundation (audit L5).

NON_SERVICE_BUILDING_TAGS module-attribute

NON_SERVICE_BUILDING_TAGS: frozenset[str] = frozenset({'carport', 'container', 'garage', 'garages', 'greenhouse', 'hut', 'no', 'roof', 'ruins', 'shed', 'shelter', 'tent'})

building=* values that usually have neither an LV service connection nor a foundation earth electrode (garages, sheds, roofs, ruins, building=no, ...). Pass it as exclude_building_tags to drop such footprints; it is not applied by default.

Point2D module-attribute

Point2D = tuple[float, float]

Type alias for a 2-D point in the local ENU frame, (x_m, y_m).

Ring module-attribute

Ring = list[Point2D]

Type alias for a closed ring; the first and last vertex are equal (or ensure_orientation() will close it).

BuildingFootprint

Bases: BaseModel

A single building's footprint, projected to the local ENU frame.

Attributes:

Name Type Description
polygon_xy_m Ring

Vertices of the exterior ring in metres, CCW. May be passed open or closed; on validation the ring is normalised to CCW and stored open (no duplicate final vertex).

holes_xy_m list[Ring]

Interior rings (holes) in metres, CW. Each hole is normalised on validation. Empty list means no holes (the typical residential case).

levels Optional[float]

building:levels tag if present (often missing in OSM). None denotes a missing value; downstream consumers default to a heuristic such as levels_default=2 for residential.

building_use Optional[str]

Value of the building=* tag (e.g. "residential", "apartments", "industrial", "yes"). Kept as the raw OSM string so the consumer can map it to a generators.building.BuildingTypeSpec at will.

osm_id Optional[int]

Original OSM way / relation id. Useful for tracing back to the source feature for debugging.

osm_tags dict[str, str]

Untouched OSM key/value tag dictionary. Lets consumers extract additional information (e.g. addr:housenumber, building:material) without going back to the source.

Notes

The instance is immutable (frozen=True) so that a generators.placement.OsmBuildingPlacement can rely on the polygon not changing while the generator iterates over sites.

area_m2

area_m2() -> float

Signed-area-based polygon area in m² (holes subtracted).

Returns:

Type Description
float

area(exterior) - sum(area(holes)), always non-negative because the rings have been normalised to CCW / CW on validation.

Source code in src/groundfield/geo/footprint.py
def area_m2(self) -> float:
    """Signed-area-based polygon area in m² (holes subtracted).

    Returns
    -------
    float
        ``area(exterior) - sum(area(holes))``, always non-negative
        because the rings have been normalised to CCW / CW on
        validation.
    """
    outer = signed_area(self.polygon_xy_m)
    inner = sum(-signed_area(h) for h in self.holes_xy_m)
    return outer - inner

axis_aligned_bounding_rectangle

axis_aligned_bounding_rectangle() -> tuple[tuple[float, float], tuple[float, float]]

Axis-aligned bounding rectangle of the exterior ring.

Returns:

Type Description
tuple

((cx, cy), (dx, dy)) — centre of the bounding box and its side lengths in metres. cx, cy are the means of the min/max coordinates; dx, dy are the absolute extents.

Notes

Pure-Python implementation; no shapely dependency. Used as a fall-back when the optional geo extra is not installed; for a fully rotated foundation electrode use oriented_bounding_rectangle() instead.

Source code in src/groundfield/geo/footprint.py
def axis_aligned_bounding_rectangle(
    self,
) -> tuple[tuple[float, float], tuple[float, float]]:
    """Axis-aligned bounding rectangle of the exterior ring.

    Returns
    -------
    tuple
        ``((cx, cy), (dx, dy))`` — centre of the bounding box and
        its side lengths in metres. ``cx``, ``cy`` are the means
        of the min/max coordinates; ``dx``, ``dy`` are the
        absolute extents.

    Notes
    -----
    Pure-Python implementation; no :mod:`shapely` dependency.
    Used as a fall-back when the optional ``geo`` extra is not
    installed; for a fully rotated foundation electrode use
    :meth:`oriented_bounding_rectangle` instead.
    """
    xs = [p[0] for p in self.polygon_xy_m]
    ys = [p[1] for p in self.polygon_xy_m]
    x_min, x_max = min(xs), max(xs)
    y_min, y_max = min(ys), max(ys)
    return (
        (0.5 * (x_min + x_max), 0.5 * (y_min + y_max)),
        (x_max - x_min, y_max - y_min),
    )

centroid_xy_m

centroid_xy_m() -> Point2D

Geometric centroid of the exterior ring in metres.

Notes

Holes are ignored — for the residential / commercial building shapes we care about, the moment shift caused by a hole is at most a few centimetres and irrelevant to the soil-spreading calculation. Implements

\[ C_x = \frac{1}{6A}\sum_{i=0}^{n-1} (x_i + x_{i+1})(x_i y_{i+1} - x_{i+1} y_i), \]

analogously for \(C_y\).

Source code in src/groundfield/geo/footprint.py
def centroid_xy_m(self) -> Point2D:
    r"""Geometric centroid of the *exterior* ring in metres.

    Notes
    -----
    Holes are ignored — for the residential / commercial
    building shapes we care about, the moment shift caused by
    a hole is at most a few centimetres and irrelevant to the
    soil-spreading calculation. Implements

    .. math::

       C_x = \frac{1}{6A}\sum_{i=0}^{n-1}
             (x_i + x_{i+1})(x_i y_{i+1} - x_{i+1} y_i),

    analogously for :math:`C_y`.
    """
    ring = self.polygon_xy_m
    a = signed_area(ring)
    if a == 0.0:
        # Degenerate ring; fall back to the vertex mean.
        xs = [p[0] for p in ring]
        ys = [p[1] for p in ring]
        return (sum(xs) / len(xs), sum(ys) / len(ys))
    cx = cy = 0.0
    n = len(ring)
    for i in range(n):
        x0, y0 = ring[i]
        x1, y1 = ring[(i + 1) % n]
        cross = x0 * y1 - x1 * y0
        cx += (x0 + x1) * cross
        cy += (y0 + y1) * cross
    denom = 6.0 * a
    return (cx / denom, cy / denom)

is_degenerate

is_degenerate() -> bool

True when the exterior ring encloses no area.

That is, its mean width is below MIN_OUTLINE_WIDTH_M (identical or collinear vertices, up to projection round-off).

Source code in src/groundfield/geo/footprint.py
def is_degenerate(self) -> bool:
    """``True`` when the exterior ring encloses no area.

    That is, its mean width is below :data:`MIN_OUTLINE_WIDTH_M`
    (identical or collinear vertices, up to projection round-off).
    """
    return self.mean_width_m() < MIN_OUTLINE_WIDTH_M

mean_width_m

mean_width_m() -> float

Mean width \(2A/P\) of the exterior ring in m (mean_width()).

Source code in src/groundfield/geo/footprint.py
def mean_width_m(self) -> float:
    """Mean width :math:`2A/P` of the exterior ring in m (:func:`mean_width`)."""
    return mean_width(self.polygon_xy_m)

oriented_bounding_rectangle

oriented_bounding_rectangle() -> tuple[tuple[float, float], tuple[float, float], float]

Oriented minimum bounding rectangle (OMBR) of the exterior ring.

Returns:

Type Description
tuple

((cx, cy), (dx, dy), orientation_deg) — centre, side lengths (dx along the local long axis, dy perpendicular), and rotation of the long axis with respect to the world +x direction in degrees. orientation_deg lies in (-90, 90]. For a square (equal sides within a relative 1e-9) the axis closest to +x is reported, i.e. orientation_deg lies in (-45, 45] — an axis-aligned square has angle 0 whatever the vertex order of the polygon. An outline without area (identical or collinear vertices) gives its covering segment: dy = 0 (and dx = 0 with angle 0 for a single point), so a caller can widen it (audit A2G-06; this raised IndexError up to 2026.11).

Notes

Uses Shapely's Polygon.minimum_rotated_rectangle, which implements the rotating-calipers algorithm. Requires the optional geo extra; raises ImportError with the install hint otherwise.

Physical interpretation

The OMBR is the canonical projection of an arbitrary building outline onto a Streifenfundament (DIN 18014): the foundation ring follows the OMBR's perimeter, so its side lengths fix the conductor length that contributes to the galvanic spreading admittance, and the orientation fixes the angle relative to the PEN trunk for the inductive-coupling calculation. For a typical residential L-shape the OMBR captures the dominant edge alignment within a few degrees; full polygonal Strip chains are deferred to Phase B (ADR-0011).

Source code in src/groundfield/geo/footprint.py
def oriented_bounding_rectangle(
    self,
) -> tuple[tuple[float, float], tuple[float, float], float]:
    r"""Oriented minimum bounding rectangle (OMBR) of the exterior
    ring.

    Returns
    -------
    tuple
        ``((cx, cy), (dx, dy), orientation_deg)`` — centre,
        side lengths (``dx`` along the local long axis, ``dy``
        perpendicular), and rotation of the long axis with
        respect to the world ``+x`` direction in degrees.
        ``orientation_deg`` lies in ``(-90, 90]``. For a square
        (equal sides within a relative ``1e-9``) the axis closest to
        ``+x`` is reported, i.e. ``orientation_deg`` lies in
        ``(-45, 45]`` — an axis-aligned square has angle 0 whatever
        the vertex order of the polygon. An outline without area
        (identical or collinear vertices) gives its covering segment:
        ``dy = 0`` (and ``dx = 0`` with angle 0 for a single point),
        so a caller can widen it (audit A2G-06; this raised
        ``IndexError`` up to 2026.11).

    Notes
    -----
    Uses Shapely's ``Polygon.minimum_rotated_rectangle``,
    which implements the rotating-calipers algorithm. Requires
    the optional ``geo`` extra; raises :class:`ImportError`
    with the install hint otherwise.

    Physical interpretation
    -----------------------
    The OMBR is the canonical projection of an arbitrary
    building outline onto a *Streifenfundament* (DIN 18014):
    the foundation ring follows the OMBR's perimeter, so its
    side lengths fix the conductor length that contributes to
    the galvanic spreading admittance, and the orientation
    fixes the angle relative to the PEN trunk for the
    inductive-coupling calculation. For a typical residential
    L-shape the OMBR captures the dominant edge alignment
    within a few degrees; full polygonal Strip chains are
    deferred to Phase B (ADR-0011).
    """
    try:
        from shapely.geometry import Polygon  # noqa: F401
    except ImportError as exc:  # pragma: no cover - exercised in tests
        from groundfield.geo.projection import GEO_IMPORT_HINT

        raise ImportError(GEO_IMPORT_HINT) from exc
    from shapely.geometry import Polygon as _Polygon

    if len(self.polygon_xy_m) < 3:
        # A closed input of three vertices with a repeated first
        # vertex is stored as two (ensure_orientation).
        return _segment_ombr(self.polygon_xy_m)
    poly = _Polygon(self.polygon_xy_m, holes=self.holes_xy_m)
    if not poly.is_valid:
        # Buffer(0) is the Shapely idiom for cleaning up
        # self-intersections that occasionally show up in OSM data.
        poly = poly.buffer(0)
    if poly.is_empty or poly.area <= 0.0:
        # Identical or collinear vertices: buffer(0) leaves an empty
        # geometry (no corners to read below).
        return _segment_ombr(self.polygon_xy_m)
    # Shapely's ``oriented_envelope`` GEOS ufunc trips benign numpy
    # divide-by-zero / invalid-value floating-point flags on
    # axis-aligned footprints (the OMBR of an axis-aligned rectangle
    # is the rectangle itself; the returned geometry is correct).
    # Silence only that specific ``RuntimeWarning`` here so it does
    # not clutter a caller's — or pytest's — warning summary.
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
            message="(divide by zero|invalid value) encountered",
            category=RuntimeWarning,
        )
        mrr = poly.minimum_rotated_rectangle
    coords = list(mrr.exterior.coords)
    # ``minimum_rotated_rectangle`` always returns five coords
    # (closed ring). The four sides connect coords[i] -> coords[i+1].
    # Pick the longer side direction as the OMBR long axis.
    import math as _math

    x0, y0 = coords[0]
    x1, y1 = coords[1]
    x2, y2 = coords[2]
    len_a = _math.hypot(x1 - x0, y1 - y0)
    len_b = _math.hypot(x2 - x1, y2 - y1)
    angle_a = _axis_angle_deg(x1 - x0, y1 - y0)
    angle_b = _axis_angle_deg(x2 - x1, y2 - y1)
    if abs(len_a - len_b) <= _SQUARE_RTOL * max(len_a, len_b):
        # A square: both sides are "the long axis". Pick the axis
        # closest to +x (ties at ±45° go to +45°), so the result does
        # not depend on GEOS's vertex order (10.39).
        angle = min((angle_a, angle_b), key=lambda a: (abs(a), -a))
        dx = dy = max(len_a, len_b)
    elif len_a > len_b:
        angle, dx, dy = angle_a, len_a, len_b
    else:
        angle, dx, dy = angle_b, len_b, len_a
    cx = sum(c[0] for c in coords[:4]) / 4.0
    cy = sum(c[1] for c in coords[:4]) / 4.0
    return ((cx, cy), (dx, dy), angle)

OsmBuildingPlacement

Bases: BaseModel

Placement driven by a list of pre-projected building footprints.

The class implements the same generate(n, rng) -> list[(x, y)] interface as generators.placement.ManhattanGridPlacement and generators.placement.ExplicitPlacement, so any consumer that accepts a PlacementSpec will accept this placement too (once it has been added to the discriminated union; see Task 3 in ADR-0011's implementation plan).

Attributes:

Name Type Description
footprints list[BuildingFootprint]

Pre-projected building polygons in the local ENU frame. Order is preserved; the k-th footprint corresponds to the k-th building site.

min_area_m2 float

Skip footprints whose area is strictly below this threshold on generate(). The default of 16 m² is roughly a garden shed; everything smaller is almost certainly OSM noise rather than a residential structure with a foundation electrode.

selection Literal['first_n', 'all']

How to choose footprints when the generator requests fewer than are available:

  • "first_n" (default) — take the first n in declared order. Fully deterministic.
  • "all" — return all footprints regardless of n. Useful when the user wants every visible building to appear in the world; n becomes a soft hint.
Notes

The class is intentionally a plain Pydantic BaseModel with a kind discriminator field; it does not inherit from a common PlacementSpec ABC because the existing union uses structural typing via the kind literal. Adding this class to generators.placement.PlacementSpec is a one-line union update tracked as a follow-up task.

n_footprints property

n_footprints: int

Number of footprints surviving the min_area_m2 filter.

Identical to len(placement) and provided as an explicit attribute so consumers can pre-flight an i against footprint_at() without invoking len() on the model instance.

__len__

__len__() -> int

Number of footprints after applying min_area_m2.

Source code in src/groundfield/geo/placement.py
def __len__(self) -> int:
    """Number of footprints after applying ``min_area_m2``."""
    return self.n_footprints

footprint_at

footprint_at(i: int, *, strict: bool = False) -> Optional[BuildingFootprint]

Return the footprint associated with site i.

Parameters:

Name Type Description Default
i int

Site index, matching the order returned by generate().

required
strict bool

If False (default), a out-of-range i returns None so callers can fall back to the spec-defined geometry without special-case logic — the historic v0.6.0 contract that TnNetworkGenerator.build() relies on.

If True, an out-of-range i raises a self-describing IndexError that names the placement, the requested index, the size of the filtered footprint list (after min_area_m2) and the raw list length. Generator pipelines that want a hard failure instead of a silent fall-back can opt in with strict=True and get an actionable traceback at the call site.

False

Returns:

Type Description
BuildingFootprint or None

The footprint at index i (after applying the min_area_m2 filter), or None when i is out of range and strict is False.

Raises:

Type Description
IndexError

If strict=True and i is outside [0, n_footprints).

Source code in src/groundfield/geo/placement.py
def footprint_at(
    self,
    i: int,
    *,
    strict: bool = False,
) -> Optional[BuildingFootprint]:
    """Return the footprint associated with site ``i``.

    Parameters
    ----------
    i
        Site index, matching the order returned by
        :meth:`generate`.
    strict
        If ``False`` (default), a out-of-range ``i`` returns
        ``None`` so callers can fall back to the spec-defined
        geometry without special-case logic — the historic
        v0.6.0 contract that
        :meth:`TnNetworkGenerator.build` relies on.

        If ``True``, an out-of-range ``i`` raises a
        self-describing :class:`IndexError` that names the
        placement, the requested index, the size of the filtered
        footprint list (after ``min_area_m2``) and the raw list
        length. Generator pipelines that want a hard failure
        instead of a silent fall-back can opt in with
        ``strict=True`` and get an actionable traceback at the
        call site.

    Returns
    -------
    BuildingFootprint or None
        The footprint at index ``i`` (after applying the
        ``min_area_m2`` filter), or ``None`` when ``i`` is out of
        range and ``strict`` is ``False``.

    Raises
    ------
    IndexError
        If ``strict=True`` and ``i`` is outside
        ``[0, n_footprints)``.
    """
    filtered = self._filtered()
    n = len(filtered)
    if 0 <= i < n:
        return filtered[i]
    if strict:
        raise IndexError(
            "OsmBuildingPlacement.footprint_at: requested index "
            f"{i} but only {n} footprints are available after "
            f"min_area_m2={self.min_area_m2} filter "
            f"(raw list length {len(self.footprints)}). "
            "Use ``len(placement)`` for the available count, or "
            "pass ``strict=False`` (default) for a None fall-back."
        )
    return None

generate

generate(n: int, rng: 'np.random.Generator') -> list[tuple[float, float]]

Return n site positions as polygon centroids.

Parameters:

Name Type Description Default
n int

Number of sites the generator wants to populate.

required
rng 'np.random.Generator'

Unused. Accepted for interface parity with the other PlacementSpec variants, all of which take an RNG so the generator can call them uniformly.

required

Returns:

Type Description
list[tuple[float, float]]

Polygon centroids in metres. Length is min(n, len(filtered)) when selection == "first_n" and equal to len(filtered) when selection == "all" (n is then ignored, with a soft contract).

Raises:

Type Description
ValueError

If n exceeds the available footprints and selection == "first_n". The generator can decide whether to widen its search radius or lower its n-target.

Notes

The reported site is the polygon's area centroid, not the centre of its oriented minimum bounding rectangle (OMBR); the two coincide only for outlines with a centre of symmetry (an L-shaped house separates them by several metres). Consumers that build OMBR-aligned geometry — i.e. footprint-driven FoundationElectrodeSpec in TnNetworkGenerator — must therefore compensate the centroid-to-OMBR-centre difference themselves via offset_xy_m. The service-drop / PEN routing consumers legitimately use the centroid, which is why generate keeps returning it.

Source code in src/groundfield/geo/placement.py
def generate(
    self,
    n: int,
    rng: "np.random.Generator",  # unused — kept for interface parity
) -> list[tuple[float, float]]:
    """Return ``n`` site positions as polygon centroids.

    Parameters
    ----------
    n
        Number of sites the generator wants to populate.
    rng
        Unused. Accepted for interface parity with the other
        :class:`PlacementSpec` variants, all of which take an
        RNG so the generator can call them uniformly.

    Returns
    -------
    list[tuple[float, float]]
        Polygon centroids in metres. Length is ``min(n,
        len(filtered))`` when ``selection == "first_n"`` and
        equal to ``len(filtered)`` when ``selection == "all"``
        (``n`` is then ignored, with a soft contract).

    Raises
    ------
    ValueError
        If ``n`` exceeds the available footprints **and**
        ``selection == "first_n"``. The generator can decide
        whether to widen its search radius or lower its
        ``n``-target.

    Notes
    -----
    The reported site is the polygon's **area centroid**, not
    the centre of its oriented minimum bounding rectangle
    (OMBR); the two coincide only for outlines with a centre of
    symmetry (an L-shaped house separates them by several
    metres). Consumers that build OMBR-aligned geometry — i.e.
    footprint-driven :class:`FoundationElectrodeSpec` in
    :class:`~groundfield.generators.tn_network.TnNetworkGenerator`
    — must therefore compensate the centroid-to-OMBR-centre
    difference themselves via ``offset_xy_m``. The service-drop
    / PEN routing consumers legitimately use the centroid,
    which is why ``generate`` keeps returning it.
    """
    filtered = self._filtered()
    if self.selection == "all":
        return [fp.centroid_xy_m() for fp in filtered]
    if n > len(filtered):
        raise ValueError(
            f"OsmBuildingPlacement.generate: requested {n} sites "
            f"but only {len(filtered)} footprints are available "
            f"after the min_area_m2={self.min_area_m2} filter."
        )
    return [filtered[i].centroid_xy_m() for i in range(n)]

OverpassError

OverpassError(message: str, *, status_code: Optional[int] = None, body: str = '')

Bases: RuntimeError

Raised on a non-success Overpass response.

Parameters:

Name Type Description Default
message str

Error message.

required
status_code int

HTTP status code of the response, if any.

None
body str

Excerpt of the response body (the callers pass its first 1 kB).

""

Attributes:

Name Type Description
status_code

HTTP status code if available, else None.

body

First 1 kB of the response body for diagnostic purposes.

Source code in src/groundfield/geo/osm.py
def __init__(
    self,
    message: str,
    *,
    status_code: Optional[int] = None,
    body: str = "",
) -> None:
    super().__init__(message)
    self.status_code = status_code
    self.body = body

Projector

Projector(lat0_deg: float, lon0_deg: float, *, ellps: str = 'WGS84')

WGS84 (longitude, latitude) <-> local ENU (x_m, y_m) projection.

Parameters:

Name Type Description Default
lat0_deg float

Latitude and longitude of the projection origin in decimal degrees, WGS84. The origin is the point that maps to (x_m, y_m) = (0, 0). The user picks it explicitly — it is never inferred from the data (see ADR-0011) so two runs over the same area at different dates produce identical metric coordinates regardless of which features appear in the underlying query.

required
lon0_deg float

Latitude and longitude of the projection origin in decimal degrees, WGS84. The origin is the point that maps to (x_m, y_m) = (0, 0). The user picks it explicitly — it is never inferred from the data (see ADR-0011) so two runs over the same area at different dates produce identical metric coordinates regardless of which features appear in the underlying query.

required
ellps str

Ellipsoid name accepted by pyproj. Defaults to "WGS84"; passed straight through.

'WGS84'
Notes

The projection is azimuthal equidistant (+proj=aeqd) centred on (lat0, lon0) with the WGS84 ellipsoid. For distances \(r \lesssim 5 \, \mathrm{km}\) around the origin the residual distortion is below \(10^{-5}\) (a few centimetres on a kilometre baseline), which is two orders of magnitude below typical OSM polygon quantisation. Conformality is not preserved exactly — for our use case (placing electrodes and measuring distances between them) equal distance to the origin is the relevant invariant, not angle preservation.

The projection is not thread-safe: each Projector holds two pyproj.Transformer instances internally; instantiate one per worker if you parallelise.

Source code in src/groundfield/geo/projection.py
def __init__(
    self,
    lat0_deg: float,
    lon0_deg: float,
    *,
    ellps: str = "WGS84",
) -> None:
    if not -90.0 <= lat0_deg <= 90.0:
        raise ValueError(
            f"Projector: lat0_deg must be in [-90, 90], got {lat0_deg}."
        )
    if not -180.0 <= lon0_deg <= 180.0:
        raise ValueError(
            f"Projector: lon0_deg must be in [-180, 180], got {lon0_deg}."
        )
    pyproj = _import_pyproj()
    self.lat0_deg = float(lat0_deg)
    self.lon0_deg = float(lon0_deg)
    self.ellps = ellps
    proj4 = (
        f"+proj=aeqd +lat_0={self.lat0_deg} +lon_0={self.lon0_deg} "
        f"+ellps={self.ellps} +units=m +no_defs"
    )
    wgs84 = "EPSG:4326"
    # ``always_xy=True`` keeps (lon, lat) tuple order, the more
    # common convention in GIS code; the public API of this class
    # still exposes (lat, lon) in argument names.
    self._fwd = pyproj.Transformer.from_crs(wgs84, proj4, always_xy=True)
    self._inv = pyproj.Transformer.from_crs(proj4, wgs84, always_xy=True)

origin

origin() -> tuple[float, float]

Return the origin as (lat_deg, lon_deg).

Source code in src/groundfield/geo/projection.py
def origin(self) -> tuple[float, float]:
    """Return the origin as ``(lat_deg, lon_deg)``."""
    return (self.lat0_deg, self.lon0_deg)

ring_to_xy_m

ring_to_xy_m(lat_lon: list[tuple[float, float]]) -> list[tuple[float, float]]

Vectorised forward projection of a list of (lat, lon).

Parameters:

Name Type Description Default
lat_lon list[tuple[float, float]]

List of WGS84 (lat_deg, lon_deg) tuples.

required

Returns:

Type Description
list[tuple[float, float]]

Same length, each tuple in local ENU metres.

Source code in src/groundfield/geo/projection.py
def ring_to_xy_m(
    self, lat_lon: list[tuple[float, float]]
) -> list[tuple[float, float]]:
    """Vectorised forward projection of a list of ``(lat, lon)``.

    Parameters
    ----------
    lat_lon
        List of WGS84 ``(lat_deg, lon_deg)`` tuples.

    Returns
    -------
    list[tuple[float, float]]
        Same length, each tuple in local ENU metres.
    """
    if not lat_lon:
        return []
    lats = [p[0] for p in lat_lon]
    lons = [p[1] for p in lat_lon]
    xs, ys = self._fwd.transform(lons, lats)
    # pyproj returns numpy arrays for vector input, but plain
    # lists/tuples for scalar input. Normalise to a list of tuples
    # so the downstream Pydantic model accepts the result without
    # numpy-vs-tuple ambiguity.
    return [(float(xs[i]), float(ys[i])) for i in range(len(lats))]

to_lat_lon

to_lat_lon(x_m: float, y_m: float) -> tuple[float, float]

Inverse of to_xy_m(): local ENU -> WGS84.

Parameters:

Name Type Description Default
x_m float

Local ENU coordinates in metres.

required
y_m float

Local ENU coordinates in metres.

required

Returns:

Type Description
tuple[float, float]

(lat_deg, lon_deg) in decimal degrees.

Source code in src/groundfield/geo/projection.py
def to_lat_lon(self, x_m: float, y_m: float) -> tuple[float, float]:
    """Inverse of :meth:`to_xy_m`: local ENU -> WGS84.

    Parameters
    ----------
    x_m, y_m
        Local ENU coordinates in metres.

    Returns
    -------
    tuple[float, float]
        ``(lat_deg, lon_deg)`` in decimal degrees.
    """
    lon, lat = self._inv.transform(x_m, y_m)
    return float(lat), float(lon)

to_xy_m

to_xy_m(lat_deg: float, lon_deg: float) -> tuple[float, float]

Project a single point WGS84 -> local ENU.

Parameters:

Name Type Description Default
lat_deg float

WGS84 coordinates of the point in decimal degrees.

required
lon_deg float

WGS84 coordinates of the point in decimal degrees.

required

Returns:

Type Description
tuple[float, float]

(x_m, y_m) in the local ENU frame. x points east, y points north, z (not returned) points up.

Source code in src/groundfield/geo/projection.py
def to_xy_m(self, lat_deg: float, lon_deg: float) -> tuple[float, float]:
    """Project a single point WGS84 -> local ENU.

    Parameters
    ----------
    lat_deg, lon_deg
        WGS84 coordinates of the point in decimal degrees.

    Returns
    -------
    tuple[float, float]
        ``(x_m, y_m)`` in the local ENU frame. ``x`` points
        east, ``y`` points north, ``z`` (not returned) points up.
    """
    x, y = self._fwd.transform(lon_deg, lat_deg)
    return float(x), float(y)

build_query

build_query(lat0_deg: float, lon0_deg: float, radius_m: float, *, timeout_s: int = DEFAULT_TIMEOUT_S) -> str

Construct the Overpass-QL query string for a buildings-in-radius lookup.

Parameters:

Name Type Description Default
lat0_deg float

Centre of the lookup in WGS84 decimal degrees.

required
lon0_deg float

Centre of the lookup in WGS84 decimal degrees.

required
radius_m float

Search radius in metres. Must be positive.

required
timeout_s int

Query timeout passed to Overpass via [timeout:…].

DEFAULT_TIMEOUT_S

Returns:

Type Description
str

A deterministic Overpass-QL query. The string is byte-identical across runs given the same inputs, so its SHA-256 hash is a stable cache key.

Raises:

Type Description
ValueError

For non-finite or out-of-range coordinates (latitude in [-90, 90], longitude in [-180, 180]), a radius outside (0, MAX_RADIUS_M] or a timeout_s outside [1, MAX_TIMEOUT_S].

TypeError

If timeout_s is not an integer (it is interpolated into the query text, so anything else could inject Overpass QL).

Source code in src/groundfield/geo/osm.py
def build_query(
    lat0_deg: float,
    lon0_deg: float,
    radius_m: float,
    *,
    timeout_s: int = DEFAULT_TIMEOUT_S,
) -> str:
    """Construct the Overpass-QL query string for a buildings-in-radius
    lookup.

    Parameters
    ----------
    lat0_deg, lon0_deg
        Centre of the lookup in WGS84 decimal degrees.
    radius_m
        Search radius in metres. Must be positive.
    timeout_s
        Query timeout passed to Overpass via ``[timeout:…]``.

    Returns
    -------
    str
        A deterministic Overpass-QL query. The string is
        byte-identical across runs given the same inputs, so its
        SHA-256 hash is a stable cache key.

    Raises
    ------
    ValueError
        For non-finite or out-of-range coordinates (latitude in
        ``[-90, 90]``, longitude in ``[-180, 180]``), a radius outside
        ``(0, MAX_RADIUS_M]`` or a ``timeout_s`` outside
        ``[1, MAX_TIMEOUT_S]``.
    TypeError
        If ``timeout_s`` is not an integer (it is interpolated into the
        query text, so anything else could inject Overpass QL).
    """
    lat0_deg, lon0_deg, radius_m = _validate_area(lat0_deg, lon0_deg, radius_m)
    timeout_s = _validate_timeout(timeout_s)
    # Float formatting kept fixed so the query string is stable
    # across platforms / locales — six decimals on lat/lon are
    # roughly 0.1 m at the equator; one decimal on radius_m is
    # 0.1 m, well below typical OSM polygon quantisation.
    lat_s = f"{lat0_deg:.6f}"
    lon_s = f"{lon0_deg:.6f}"
    r_s = f"{radius_m:.1f}"
    return (
        f"[out:json][timeout:{timeout_s}];\n"
        f"(\n"
        f'  way["building"](around:{r_s},{lat_s},{lon_s});\n'
        f'  relation["building"](around:{r_s},{lat_s},{lon_s});\n'
        f");\n"
        f"out body geom tags;"
    )

default_cache_dir

default_cache_dir() -> Path

Return the default on-disk Overpass cache directory.

Honours XDG_CACHE_HOME when set; otherwise falls back to ~/.cache/groundfield/osm on Linux/macOS and the equivalent on Windows via pathlib.Path.home.

The directory is not created here; the caller (e.g. query_buildings()) creates it on first write.

Returns:

Type Description
Path

$XDG_CACHE_HOME/groundfield/osm when the variable is set and not empty, else ~/.cache/groundfield/osm.

Source code in src/groundfield/geo/osm.py
def default_cache_dir() -> Path:
    """Return the default on-disk Overpass cache directory.

    Honours ``XDG_CACHE_HOME`` when set; otherwise falls back to
    ``~/.cache/groundfield/osm`` on Linux/macOS and the equivalent
    on Windows via :class:`pathlib.Path.home`.

    The directory is *not* created here; the caller (e.g.
    :func:`query_buildings`) creates it on first write.

    Returns
    -------
    pathlib.Path
        ``$XDG_CACHE_HOME/groundfield/osm`` when the variable is set and
        not empty, else ``~/.cache/groundfield/osm``.
    """
    xdg = os.environ.get("XDG_CACHE_HOME")
    if xdg:
        return Path(xdg) / "groundfield" / "osm"
    return Path.home() / ".cache" / "groundfield" / "osm"

ensure_orientation

ensure_orientation(ring: Ring, *, ccw: bool = True) -> Ring

Return ring reordered so its signed area has the requested sign.

Parameters:

Name Type Description Default
ring Ring

Input ring (open or closed).

required
ccw bool

If True (default), the returned ring is counter-clockwise (positive signed area); if False, clockwise.

True

Returns:

Type Description
list[Point2D]

A new list of vertices in the requested orientation. The ring is returned open (no duplicate final vertex) so that the caller can close it explicitly if needed.

Source code in src/groundfield/geo/footprint.py
def ensure_orientation(ring: Ring, *, ccw: bool = True) -> Ring:
    """Return ``ring`` reordered so its signed area has the requested sign.

    Parameters
    ----------
    ring
        Input ring (open or closed).
    ccw
        If ``True`` (default), the returned ring is counter-clockwise
        (positive signed area); if ``False``, clockwise.

    Returns
    -------
    list[Point2D]
        A *new* list of vertices in the requested orientation. The
        ring is returned open (no duplicate final vertex) so that
        the caller can close it explicitly if needed.
    """
    cleaned: Ring = list(ring)
    if cleaned and cleaned[0] == cleaned[-1]:
        cleaned = cleaned[:-1]
    a = signed_area(cleaned)
    if (a > 0) != ccw:
        cleaned.reverse()
    return cleaned

mean_width

mean_width(ring: Ring) -> float

Mean width \(w = 2A/P\) of a ring in m.

Parameters:

Name Type Description Default
ring Ring

Vertex list in m (open or closed).

required

Returns:

Type Description
float

Twice the absolute area \(A\) over the perimeter \(P\): \(d_y\) for a thin \(d_x \times d_y\) rectangle (\(d_y \ll d_x\)), \(d/2\) for a square of side \(d\), and 0 for identical or collinear vertices (also for an empty ring).

Source code in src/groundfield/geo/footprint.py
def mean_width(ring: Ring) -> float:
    r"""Mean width :math:`w = 2A/P` of a ring in m.

    Parameters
    ----------
    ring
        Vertex list in m (open or closed).

    Returns
    -------
    float
        Twice the absolute area :math:`A` over the perimeter :math:`P`:
        :math:`d_y` for a thin :math:`d_x \times d_y` rectangle
        (:math:`d_y \ll d_x`), :math:`d/2` for a square of side
        :math:`d`, and 0 for identical or collinear vertices (also for
        an empty ring).
    """
    n = len(ring)
    perimeter = 0.0
    for i in range(n):
        x0, y0 = ring[i]
        x1, y1 = ring[(i + 1) % n]
        perimeter += math.hypot(x1 - x0, y1 - y0)
    if perimeter <= 0.0:
        return 0.0
    return 2.0 * abs(signed_area(ring)) / perimeter

parse_overpass_payload

parse_overpass_payload(payload: dict[str, Any], projector: Projector, *, min_area_m2: float = 0.0, exclude_building_tags: Optional[Collection[str]] = None) -> list[BuildingFootprint]

Convert an Overpass JSON payload into projected BuildingFootprint instances.

Parameters:

Name Type Description Default
payload dict[str, Any]

Overpass JSON as returned by query_buildings().

required
projector Projector

Projection from WGS84 to the local ENU frame. The same projector should be reused across all consumers of one payload to keep the metric coordinates consistent.

required
min_area_m2 float

Skip features whose footprint area is strictly below this threshold. 0.0 (the default) keeps every valid polygon; the placement layer may apply its own (higher) threshold via OsmBuildingPlacement.min_area_m2.

0.0
exclude_building_tags Optional[Collection[str]]

building=* values to drop (e.g. NON_SERVICE_BUILDING_TAGS). None (default) keeps every element with a building tag — including garages, sheds and building=no.

None

Returns:

Type Description
list[BuildingFootprint]

Order matches the Overpass element order, which Overpass keeps deterministic for the same query.

Raises:

Type Description
OverpassError

If the payload does not have the structure of an Overpass result or a vertex is not a finite WGS84 coordinate (see the module docstring). Elements whose geometry contains null vertices or that do not form a valid polygon are skipped: fewer than three vertices, or an outline without area (mean width below MIN_OUTLINE_WIDTH_M, i.e. identical or collinear vertices; audit A2G-06).

Notes

Multipolygon relations (type=multipolygon) are handled by walking the relation's members and treating each outer way as an independent footprint with the inner ways of the same relation attached as holes. Relations without an outer member are skipped.

Source code in src/groundfield/geo/osm.py
def parse_overpass_payload(
    payload: dict[str, Any],
    projector: Projector,
    *,
    min_area_m2: float = 0.0,
    exclude_building_tags: Optional[Collection[str]] = None,
) -> list[BuildingFootprint]:
    """Convert an Overpass JSON payload into projected
    :class:`BuildingFootprint` instances.

    Parameters
    ----------
    payload
        Overpass JSON as returned by :func:`query_buildings`.
    projector
        Projection from WGS84 to the local ENU frame. The same
        projector should be reused across all consumers of one
        payload to keep the metric coordinates consistent.
    min_area_m2
        Skip features whose footprint area is strictly below this
        threshold. ``0.0`` (the default) keeps every valid polygon;
        the placement layer may apply its own (higher) threshold via
        :class:`OsmBuildingPlacement.min_area_m2`.
    exclude_building_tags
        ``building=*`` values to drop (e.g.
        :data:`NON_SERVICE_BUILDING_TAGS`). ``None`` (default) keeps
        every element with a ``building`` tag — including garages,
        sheds and ``building=no``.

    Returns
    -------
    list[BuildingFootprint]
        Order matches the Overpass element order, which Overpass
        keeps deterministic for the same query.

    Raises
    ------
    OverpassError
        If the payload does not have the structure of an Overpass result
        or a vertex is not a finite WGS84 coordinate (see the module
        docstring). Elements whose geometry contains ``null`` vertices or
        that do not form a valid polygon are skipped: fewer than three
        vertices, or an outline without area (mean width below
        :data:`~groundfield.geo.footprint.MIN_OUTLINE_WIDTH_M`, i.e.
        identical or collinear vertices; audit A2G-06).

    Notes
    -----
    *Multipolygon relations* (``type=multipolygon``) are handled by
    walking the relation's ``members`` and treating each ``outer``
    way as an independent footprint with the ``inner`` ways of the
    *same* relation attached as holes. Relations without an
    ``outer`` member are skipped.
    """
    _check_payload(payload)
    elements = payload.get("elements", []) or []
    if isinstance(exclude_building_tags, str):
        exclude_building_tags = (exclude_building_tags,)
    excluded = frozenset(exclude_building_tags or ())
    by_id: dict[int, dict[str, Any]] = {
        e["id"]: e for e in elements if e.get("type") == "way" and "id" in e
    }
    out: list[BuildingFootprint] = []

    for el in elements:
        if (el.get("tags") or {}).get("building") in excluded:
            continue
        kind = el.get("type")
        if kind == "way":
            # Skip ways that belong to a multipolygon relation —
            # they would otherwise be emitted twice. Overpass does
            # not mark this directly, so for v1 we accept the
            # duplication; downstream consumers can de-duplicate
            # by ``osm_id`` if needed. The duplicate cost is small
            # because residential ways in OSM are usually standalone.
            ring_ll = _element_to_lat_lon_ring(el)
            if ring_ll is None or len(ring_ll) < 3:
                continue
            try:
                ring_xy: Ring = projector.ring_to_xy_m(ring_ll)
                fp = BuildingFootprint(
                    polygon_xy_m=ring_xy,
                    holes_xy_m=[],
                    levels=_levels_from_tags(el.get("tags") or {}),
                    building_use=(el.get("tags") or {}).get("building"),
                    osm_id=el.get("id"),
                    osm_tags=dict(el.get("tags") or {}),
                )
            except ValueError:
                continue
            if fp.is_degenerate() or fp.area_m2() < min_area_m2:
                continue
            out.append(fp)
        elif kind == "relation":
            tags = el.get("tags") or {}
            if tags.get("type") != "multipolygon":
                continue
            members = el.get("members") or []
            outers: list[list[tuple[float, float]]] = []
            inners: list[list[tuple[float, float]]] = []
            for m in members:
                if m.get("type") != "way":
                    continue
                role = m.get("role")
                ring_ll = _element_to_lat_lon_ring(m)
                if ring_ll is None:
                    # Try the referenced way from the same payload.
                    ref = by_id.get(m.get("ref"))
                    if ref is not None:
                        ring_ll = _element_to_lat_lon_ring(ref)
                if ring_ll is None or len(ring_ll) < 3:
                    continue
                if role == "outer":
                    outers.append(ring_ll)
                elif role == "inner":
                    inners.append(ring_ll)
            if not outers:
                continue
            # v1: emit each ``outer`` ring as a separate footprint
            # carrying the *full* list of inner holes. Hole-to-outer
            # assignment by winding-rule is deferred (rare in
            # residential OSM data; multipolygon buildings are
            # almost always Gewerbe-/Industriebauten with at most
            # one outer).
            for outer_ll in outers:
                try:
                    outer_xy = projector.ring_to_xy_m(outer_ll)
                    holes_xy = [projector.ring_to_xy_m(h) for h in inners]
                    fp = BuildingFootprint(
                        polygon_xy_m=outer_xy,
                        holes_xy_m=holes_xy,
                        levels=_levels_from_tags(tags),
                        building_use=tags.get("building"),
                        osm_id=el.get("id"),
                        osm_tags=dict(tags),
                    )
                except ValueError:
                    continue
                if fp.is_degenerate() or fp.area_m2() < min_area_m2:
                    continue
                out.append(fp)
        # Nodes are silently ignored: a building cannot be a node.
    return out

query_and_project

query_and_project(lat0_deg: float, lon0_deg: float, radius_m: float, *, projector: Optional[Projector] = None, cache_dir: Optional[Path] = None, endpoint: str = DEFAULT_ENDPOINT, timeout_s: int = DEFAULT_TIMEOUT_S, min_area_m2: float = 0.0, force_refresh: bool = False, max_retries: int = 1, exclude_building_tags: Optional[Collection[str]] = None, max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES, _post: Any = None) -> tuple[list[BuildingFootprint], Projector]

Run query_buildings() and parse_overpass_payload() end-to-end.

Parameters:

Name Type Description Default
lat0_deg float

Buildings-in-radius parameters.

required
lon0_deg float

Buildings-in-radius parameters.

required
radius_m float

Buildings-in-radius parameters.

required
projector Optional[Projector]

If None, a new Projector centred at (lat0_deg, lon0_deg) is created. Pass an existing projector to keep the metric frame consistent across multiple calls (useful when a study spans several overlapping radii).

None
cache_dir Optional[Path]

Forwarded to query_buildings().

None
endpoint Optional[Path]

Forwarded to query_buildings().

None
timeout_s Optional[Path]

Forwarded to query_buildings().

None
force_refresh Optional[Path]

Forwarded to query_buildings().

None
min_area_m2 float

Skip features below this footprint area. Defaults to 0.0 (keep everything; the placement layer applies its own threshold).

0.0
max_retries int

Number of retry attempts on 429 / 503 / 504 responses. Forwarded to query_buildings(). Defaults to 1.

1
exclude_building_tags Optional[Collection[str]]

Forwarded to parse_overpass_payload() (default: keep every building tag).

None
max_response_bytes int

Forwarded to query_buildings().

DEFAULT_MAX_RESPONSE_BYTES
_post Any

Test hook, forwarded to query_buildings().

None

Returns:

Type Description
tuple[list[BuildingFootprint], Projector]

Projected footprints and the projector used. The projector is returned so the caller can re-use it for further coordinate transforms (e.g. plotting a substation marker at a known lat/lon).

Source code in src/groundfield/geo/osm.py
def query_and_project(
    lat0_deg: float,
    lon0_deg: float,
    radius_m: float,
    *,
    projector: Optional[Projector] = None,
    cache_dir: Optional[Path] = None,
    endpoint: str = DEFAULT_ENDPOINT,
    timeout_s: int = DEFAULT_TIMEOUT_S,
    min_area_m2: float = 0.0,
    force_refresh: bool = False,
    max_retries: int = 1,
    exclude_building_tags: Optional[Collection[str]] = None,
    max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
    _post: Any = None,
) -> tuple[list[BuildingFootprint], Projector]:
    """Run :func:`query_buildings` and :func:`parse_overpass_payload`
    end-to-end.

    Parameters
    ----------
    lat0_deg, lon0_deg, radius_m
        Buildings-in-radius parameters.
    projector
        If ``None``, a new :class:`Projector` centred at
        ``(lat0_deg, lon0_deg)`` is created. Pass an existing
        projector to keep the metric frame consistent across
        multiple calls (useful when a study spans several
        overlapping radii).
    cache_dir, endpoint, timeout_s, force_refresh
        Forwarded to :func:`query_buildings`.
    min_area_m2
        Skip features below this footprint area. Defaults to
        ``0.0`` (keep everything; the placement layer applies its
        own threshold).
    max_retries
        Number of retry attempts on ``429`` / ``503`` / ``504``
        responses. Forwarded to :func:`query_buildings`. Defaults to
        ``1``.
    exclude_building_tags
        Forwarded to :func:`parse_overpass_payload` (default: keep every
        building tag).
    max_response_bytes
        Forwarded to :func:`query_buildings`.
    _post
        Test hook, forwarded to :func:`query_buildings`.

    Returns
    -------
    tuple[list[BuildingFootprint], Projector]
        Projected footprints and the projector used. The projector
        is returned so the caller can re-use it for further
        coordinate transforms (e.g. plotting a substation marker
        at a known lat/lon).
    """
    payload = query_buildings(
        lat0_deg,
        lon0_deg,
        radius_m,
        cache_dir=cache_dir,
        endpoint=endpoint,
        timeout_s=timeout_s,
        force_refresh=force_refresh,
        max_retries=max_retries,
        max_response_bytes=max_response_bytes,
        _post=_post,
    )
    if projector is None:
        projector = Projector(lat0_deg, lon0_deg)
    footprints = parse_overpass_payload(
        payload,
        projector,
        min_area_m2=min_area_m2,
        exclude_building_tags=exclude_building_tags,
    )
    return footprints, projector

query_buildings

query_buildings(lat0_deg: float, lon0_deg: float, radius_m: float, *, cache_dir: Optional[Path] = None, endpoint: str = DEFAULT_ENDPOINT, timeout_s: int = DEFAULT_TIMEOUT_S, force_refresh: bool = False, max_retries: int = 1, max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES, _post: Any = None) -> dict[str, Any]

Fetch (or load from cache) the raw Overpass response.

Parameters:

Name Type Description Default
lat0_deg float

Centre of the buildings-in-radius lookup, WGS84 degrees.

required
lon0_deg float

Centre of the buildings-in-radius lookup, WGS84 degrees.

required
radius_m float

Search radius in metres, at most MAX_RADIUS_M.

required
cache_dir Optional[Path]

Directory in which the response is cached. Defaults to default_cache_dir(). Created on first write.

None
endpoint str

Overpass endpoint URL (https; http only for localhost). Defaults to the canonical mirror.

DEFAULT_ENDPOINT
timeout_s int

Per-query timeout in s passed to Overpass, an integer in [1, MAX_TIMEOUT_S].

DEFAULT_TIMEOUT_S
force_refresh bool

If True, ignore any cached payload and re-query the endpoint, overwriting the cache file. Useful when the user knows the upstream data changed.

False
max_retries int

Number of retry attempts on 429 / 503 / 504 responses, in [0, MAX_RETRIES]. Defaults to 1 (one retry, matching the historic behaviour).

1
max_response_bytes int

Cap on the response size in bytes (default DEFAULT_MAX_RESPONSE_BYTES).

DEFAULT_MAX_RESPONSE_BYTES
_post Any

Internal hook for tests: a callable with the signature (query, *, endpoint, timeout_s, max_retries). Production calls use _post_overpass().

None

Returns:

Type Description
dict[str, Any]

The decoded Overpass JSON payload. The shape is {"version": …, "generator": …, "elements": [...]}; only elements is required downstream.

Raises:

Type Description
OverpassError

On HTTP errors, oversized or malformed responses and payloads whose remark reports an Overpass runtime error (such a payload is not cached).

(ValueError, TypeError)

For invalid arguments (see build_query()).

Notes

The cache filename is <sha256(query)>.json for the default endpoint and <sha256(endpoint + newline + query)>.json for any other endpoint. Files are written atomically; a cache file that cannot be read back is re-fetched (with a UserWarning).

Source code in src/groundfield/geo/osm.py
def query_buildings(
    lat0_deg: float,
    lon0_deg: float,
    radius_m: float,
    *,
    cache_dir: Optional[Path] = None,
    endpoint: str = DEFAULT_ENDPOINT,
    timeout_s: int = DEFAULT_TIMEOUT_S,
    force_refresh: bool = False,
    max_retries: int = 1,
    max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
    _post: Any = None,
) -> dict[str, Any]:
    """Fetch (or load from cache) the raw Overpass response.

    Parameters
    ----------
    lat0_deg, lon0_deg
        Centre of the buildings-in-radius lookup, WGS84 degrees.
    radius_m
        Search radius in metres, at most :data:`MAX_RADIUS_M`.
    cache_dir
        Directory in which the response is cached. Defaults to
        :func:`default_cache_dir`. Created on first write.
    endpoint
        Overpass endpoint URL (``https``; ``http`` only for
        ``localhost``). Defaults to the canonical mirror.
    timeout_s
        Per-query timeout in s passed to Overpass, an integer in
        ``[1, MAX_TIMEOUT_S]``.
    force_refresh
        If ``True``, ignore any cached payload and re-query the
        endpoint, overwriting the cache file. Useful when the user
        knows the upstream data changed.
    max_retries
        Number of retry attempts on ``429`` / ``503`` / ``504``
        responses, in ``[0, MAX_RETRIES]``. Defaults to ``1`` (one
        retry, matching the historic behaviour).
    max_response_bytes
        Cap on the response size in bytes (default
        :data:`DEFAULT_MAX_RESPONSE_BYTES`).
    _post
        Internal hook for tests: a callable with the signature
        ``(query, *, endpoint, timeout_s, max_retries)``. Production
        calls use :func:`_post_overpass`.

    Returns
    -------
    dict[str, Any]
        The decoded Overpass JSON payload. The shape is
        ``{"version": …, "generator": …, "elements": [...]}``;
        only ``elements`` is required downstream.

    Raises
    ------
    OverpassError
        On HTTP errors, oversized or malformed responses and payloads
        whose ``remark`` reports an Overpass runtime error (such a
        payload is not cached).
    ValueError, TypeError
        For invalid arguments (see :func:`build_query`).

    Notes
    -----
    The cache filename is ``<sha256(query)>.json`` for the default
    endpoint and ``<sha256(endpoint + newline + query)>.json`` for any
    other endpoint. Files are written atomically; a cache file that
    cannot be read back is re-fetched (with a :class:`UserWarning`).
    """
    _validate_max_retries(max_retries)
    max_response_bytes = _validate_max_response_bytes(max_response_bytes)
    endpoint = _validate_endpoint(endpoint)
    cache_dir = cache_dir if cache_dir is not None else default_cache_dir()
    query = build_query(lat0_deg, lon0_deg, radius_m, timeout_s=timeout_s)
    path = Path(cache_dir) / f"{_cache_key(query, endpoint)}.json"
    if path.exists() and not force_refresh:
        try:
            with path.open("r", encoding="utf-8") as fh:
                return _check_payload(json.load(fh))
        except (ValueError, RecursionError, OverpassError) as exc:
            warnings.warn(
                f"Overpass cache file {path.name} is unreadable ({exc}); re-fetching.",
                UserWarning,
                stacklevel=2,
            )
    if _post is not None:
        post = _post
    else:
        post = functools.partial(_post_overpass, max_response_bytes=max_response_bytes)
    payload = post(
        query,
        endpoint=endpoint,
        timeout_s=timeout_s,
        max_retries=max_retries,
    )
    _check_payload(payload)
    _atomic_write_json(path, payload)
    return payload

signed_area

signed_area(ring: Ring) -> float

Signed area of a polygon ring via the shoelace formula.

Parameters:

Name Type Description Default
ring Ring

Vertex list. The ring may be open (last vertex != first); the shoelace formula closes it implicitly.

required

Returns:

Type Description
float

Signed area in m². Positive for counter-clockwise rings, negative for clockwise rings, zero for degenerate rings.

Notes

Implements

\[ A \;=\; \tfrac{1}{2}\sum_{i=0}^{n-1}\bigl(x_i\,y_{i+1}\;-\; x_{i+1}\,y_i\bigr) \]

with indices taken modulo n. The orientation convention used here (CCW positive) matches the right-hand rule with a z-axis pointing out of the ground in the local ENU frame.

Source code in src/groundfield/geo/footprint.py
def signed_area(ring: Ring) -> float:
    r"""Signed area of a polygon ring via the shoelace formula.

    Parameters
    ----------
    ring
        Vertex list. The ring may be open (last vertex != first); the
        shoelace formula closes it implicitly.

    Returns
    -------
    float
        Signed area in m². Positive for counter-clockwise rings,
        negative for clockwise rings, zero for degenerate rings.

    Notes
    -----
    Implements

    .. math::

       A \;=\; \tfrac{1}{2}\sum_{i=0}^{n-1}\bigl(x_i\,y_{i+1}\;-\;
                                                x_{i+1}\,y_i\bigr)

    with indices taken modulo *n*. The orientation convention used
    here (CCW positive) matches the right-hand rule with a
    z-axis pointing *out of the ground* in the local ENU frame.
    """
    n = len(ring)
    if n < 3:
        return 0.0
    s = 0.0
    for i in range(n):
        x0, y0 = ring[i]
        x1, y1 = ring[(i + 1) % n]
        s += x0 * y1 - x1 * y0
    return 0.5 * s