Source code for rapidtools.processing.aerial_evidence

# Copyright (c) 2025 The University of Washington
#
# This file is part of rapidtools.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You should have received a copy of the BSD 3-Clause License along with
# rapidtools. If not, see <http://www.opensource.org/licenses/>.
#
# Contributors:
# Barbaros Cetiner
#
#
# Last updated:
# 11-27-2026

"""
What an overhead image says about the ground, for occupancy fusion.

Street-level frames see an object from the side; an orthomosaic sees it
from above. :func:`~rapidtools.processing.street_fusion.fuse_observations`
reads both as evidence on the same ground grid. The overhead view tells
three things about each cell, for one class of object:

- *occupied* where a detection outline covers it;
- *empty* where the detector looked, could see the ground, and found
  nothing;
- *nothing* where it did not look (outside ``coverage``) or could not see
  the ground (under ``occluders``: tree crowns, roofs, bridges). A hydrant
  under a tree is not absent because the tree hides it.

How much each answer weighs comes from three numbers that describe the
detector on this class, not from rules: its ``recall`` (the share of the
objects it finds where it can see them), its ``false_alarm`` rate (the
share of empty ground it marks) and the ``persistence`` of the class
between the two captures (``1`` for things that do not move; less for
parked cars photographed hours apart). A detector that rarely finds a
class (a hydrant in 60 cm satellite imagery) has a low recall, so its
silence weighs almost nothing and it cannot clear what the street frames
saw.

Nothing in this module runs a model: the detections can come from
:class:`~rapidtools.processing.SAM3OrthoFeatureExtractor`, from another
detector, or from a hand-drawn layer.

Example:
    >>> from shapely.geometry import box
    >>> evidence = AerialEvidence([box(-117.4, 47.7, -117.39995, 47.70002)],
    ...                           recall=0.9, false_alarm=0.01)
    >>> round(evidence.hit_log_odds, 2), round(evidence.miss_log_odds, 2)
    (4.5, -2.29)
"""

from __future__ import annotations

import json
import math
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import numpy as np
from rasterio.features import rasterize
from rasterio.transform import from_origin
from scipy.spatial import cKDTree
from shapely import STRtree
from shapely.geometry import MultiPolygon, Polygon, box, shape
from shapely.geometry.base import BaseGeometry
from shapely.ops import transform as shapely_transform
from shapely.ops import unary_union

Project = Callable[[float, float], tuple[float, float]]


def _polygons(geometry: BaseGeometry | None) -> list[Polygon]:
    """The polygonal parts of a geometry, empty parts dropped."""
    if geometry is None or geometry.is_empty:
        return []
    if isinstance(geometry, Polygon):
        return [geometry]
    if isinstance(geometry, MultiPolygon):
        return [g for g in geometry.geoms if not g.is_empty]
    parts = getattr(geometry, 'geoms', None)
    if parts is None:
        return []
    return [p for g in parts for p in _polygons(g)]


def _load_geometries(source: Any) -> list[tuple[BaseGeometry, dict[str, Any]]]:
    """
    Geometries and attributes from a collection, a GeoJSON path or a list.

    Accepts a :class:`~rapidtools.core.PhysicalAssetCollection` (or any
    iterable of objects with ``geometry`` and ``attributes``), the path of a
    GeoJSON file, or a sequence of shapely geometries.
    """
    if source is None:
        return []
    if isinstance(source, BaseGeometry):
        return [(source, {})]
    if isinstance(source, (str, Path)):
        with open(source, encoding='utf-8') as handle:
            data = json.load(handle)
        features = data.get('features', []) if isinstance(data, dict) else []
        return [
            (shape(f['geometry']), dict(f.get('properties') or {}))
            for f in features
            if f.get('geometry')
        ]
    out: list[tuple[BaseGeometry, dict[str, Any]]] = []
    for item in source:
        if isinstance(item, BaseGeometry):
            out.append((item, {}))
        else:
            out.append((item.geometry, dict(getattr(item, 'attributes', {}) or {})))
    return out


def _union(source: Any) -> BaseGeometry | None:
    """One geometry covering everything in ``source`` (``None`` if empty)."""
    if source is None:
        return None
    if isinstance(source, BaseGeometry):
        return source
    parts = [p for g, _ in _load_geometries(source) for p in _polygons(g)]
    return unary_union(parts) if parts else None


[docs] @dataclass class AerialEvidence: """ The detections of one class in an overhead image, with what they weigh. Attributes: detections: Outlines of the detected objects (or areas, for surface classes such as driveways) in longitude and latitude. Distinct outlines are distinct objects: fusion splits a blob that two of them share. coverage: The ground the detector looked at, in longitude and latitude (for :class:`~rapidtools.processing.SAM3OrthoFeatureExtractor`, its ``scanned_area`` after a scan). ``None`` uses the detections as positive evidence only: the image then never says a cell is empty. occluders: Ground the overhead view cannot see for this class (tree crowns over a curb, roofs, carports), in longitude and latitude. Silence there says nothing. recall: Share of the objects the detector finds where it can see them. false_alarm: Share of empty, visible ground it marks as the class. persistence: Chance that a spot holds the same thing at the time of the overhead image and at the time of the street survey: ``1`` for objects that do not move, lower for parked cars. offset_m: ``(east, north)`` shift in meters added to every outline to line the image up with the street survey's camera positions (see :func:`estimate_offset`). scores: Detector confidence of each outline, if known. Example: >>> from shapely.geometry import box >>> moved = AerialEvidence([box(0, 0, 1e-5, 1e-5)], persistence=0.5) >>> moved.hit_log_odds, moved.miss_log_odds (0.0, 0.0) """ detections: list[BaseGeometry] coverage: BaseGeometry | None = None occluders: BaseGeometry | None = None recall: float = 0.9 false_alarm: float = 0.01 persistence: float = 1.0 offset_m: tuple[float, float] = (0.0, 0.0) scores: list[float | None] = field(default_factory=list) def __post_init__(self) -> None: if not 0.0 < self.recall < 1.0: raise ValueError('recall must be between 0 and 1 (exclusive).') if not 0.0 < self.false_alarm < self.recall: raise ValueError('false_alarm must be above 0 and below recall.') if not 0.5 <= self.persistence <= 1.0: raise ValueError('persistence must be between 0.5 and 1.')
[docs] @classmethod def from_assets( cls, source: Any, *, coverage: Any = None, occluders: Any = None, min_confidence: float | None = None, **settings: Any, ) -> AerialEvidence: """ Build the evidence from detected assets. Args: source: The detections: a :class:`~rapidtools.core.PhysicalAssetCollection` (such as the output of :class:`~rapidtools.processing.SAM3OrthoFeatureExtractor`), the path of a GeoJSON file, or a sequence of polygons, all in longitude and latitude. coverage: Ground the detector looked at, in any of the same forms or as one geometry. occluders: Ground the overhead view cannot see, in any of the same forms. min_confidence: Detections whose ``confidence`` attribute is below this are left out. **settings: The remaining :class:`AerialEvidence` fields (``recall``, ``false_alarm``, ``persistence``, ``offset_m``). Returns: AerialEvidence: The evidence, with one outline per polygonal detection and its confidence in ``scores``. Example: >>> from shapely.geometry import box >>> evidence = AerialEvidence.from_assets( ... [box(0, 0, 1e-5, 1e-5)], coverage=box(-1e-4, -1e-4, 1e-4, 1e-4) ... ) >>> len(evidence.detections), evidence.coverage is not None (1, True) """ detections: list[BaseGeometry] = [] scores: list[float | None] = [] for geometry, attributes in _load_geometries(source): if not _polygons(geometry): continue confidence = attributes.get('confidence') if ( min_confidence is not None and confidence is not None and float(confidence) < min_confidence ): continue detections.append(geometry) scores.append(None if confidence is None else float(confidence)) return cls( detections, coverage=_union(coverage), occluders=_union(occluders), scores=scores, **settings, )
def _likelihoods(self) -> tuple[float, float]: """Chance of a detection on an occupied and on an empty cell.""" q, r, f = self.persistence, self.recall, self.false_alarm # The spot holds the same thing at both times with chance q; when it # does not, an occupied spot was empty in the image and vice versa. return q * r + (1.0 - q) * f, q * f + (1.0 - q) * r @property def hit_log_odds(self) -> float: """Log-odds a detection adds to a cell's chance of being occupied.""" occupied, empty = self._likelihoods() return float(math.log(occupied / empty)) @property def miss_log_odds(self) -> float: """Log-odds that visible ground without a detection adds (negative).""" occupied, empty = self._likelihoods() return float(math.log((1.0 - occupied) / (1.0 - empty)))
[docs] def to_local(self, project: Project) -> LocalAerialEvidence: """ The evidence in a local meter frame, ready to be laid on grids. Args: project: ``(lon, lat) -> (x, y)`` in meters, such as the first function returned by :func:`~rapidtools.processing.street_localization.local_projection`. Returns: LocalAerialEvidence: Outlines, coverage and occluders in meters, shifted by ``offset_m``. """ dx, dy = self.offset_m def to_meters(x: Any, y: Any, z: Any = None) -> tuple[Any, Any]: xs, ys = np.atleast_1d(x), np.atleast_1d(y) pts = [project(float(a), float(b)) for a, b in zip(xs, ys, strict=True)] return np.array([p[0] for p in pts]) + dx, np.array( [p[1] for p in pts] ) + dy def local(geometry: BaseGeometry | None) -> BaseGeometry | None: if geometry is None or geometry.is_empty: return None return shapely_transform(to_meters, geometry) outlines = [local(g) for g in self.detections] return LocalAerialEvidence( detections=[g for g in outlines if g is not None], coverage=local(self.coverage), occluders=local(self.occluders), hit=self.hit_log_odds, miss=self.miss_log_odds if self.coverage is not None else 0.0, )
[docs] @dataclass class LocalAerialEvidence: """ Aerial evidence in a local meter frame (see :meth:`AerialEvidence.to_local`). Attributes: detections: Outlines in meters. coverage: Ground the detector looked at, or ``None``. occluders: Ground it cannot see, or ``None``. hit: Log-odds added inside an outline. miss: Log-odds added on visible ground without one. """ detections: list[BaseGeometry] coverage: BaseGeometry | None occluders: BaseGeometry | None hit: float miss: float _tree: STRtree | None = field(default=None, init=False, repr=False) def __post_init__(self) -> None: self._tree = STRtree(self.detections) if self.detections else None
[docs] def detections_in(self, bounds: tuple[float, float, float, float]) -> list[int]: """Indices of the outlines that reach into ``(x0, y0, x1, y1)``.""" if self._tree is None: return [] return [int(i) for i in self._tree.query(box(*bounds))]
[docs] def layers( self, x0: float, y0: float, cell: float, nx: int, ny: int ) -> tuple[np.ndarray, np.ndarray]: """ Lay the evidence on a grid of ``ny`` rows by ``nx`` columns. Row ``j`` and column ``i`` are the cell whose lower left corner is ``(x0 + i * cell, y0 + j * cell)``. A cell counts as covered by a shape when its center lies inside it. Returns: tuple[numpy.ndarray, numpy.ndarray]: The log-odds per cell (``hit`` inside an outline, ``miss`` on visible ground in the coverage, ``0`` elsewhere) and the outline per cell (index into ``detections`` plus one; ``0`` for none). Example: >>> from shapely.geometry import box >>> local = LocalAerialEvidence([box(1, 1, 2, 2)], box(0, 0, 4, 4), None, ... 2.0, -1.0) >>> log_odds, outline = local.layers(0.0, 0.0, 0.5, 8, 8) >>> int((outline == 1).sum()), float(log_odds[0, 0]), float(log_odds[3, 3]) (4, -1.0, 2.0) """ transform = from_origin(x0, y0 + ny * cell, cell, cell) def burn(shapes: list[tuple[BaseGeometry, int]]) -> np.ndarray: if not shapes: return np.zeros((ny, nx), np.int32) raster = rasterize( shapes, out_shape=(ny, nx), transform=transform, fill=0, dtype='int32', ) return np.ascontiguousarray(raster[::-1]) # row 0 is the south edge frame = (x0, y0, x0 + nx * cell, y0 + ny * cell) window = box(*frame) log_odds = np.zeros((ny, nx), np.float32) if self.coverage is not None and self.miss != 0.0: seen = burn([(g, 1) for g in _polygons(self.coverage.intersection(window))]) if self.occluders is not None: hidden = burn( [(g, 1) for g in _polygons(self.occluders.intersection(window))] ) seen[hidden > 0] = 0 log_odds[seen > 0] = self.miss outline = burn( [ (self.detections[i], i + 1) for i in self.detections_in(frame) if _polygons(self.detections[i]) ] ) log_odds[outline > 0] = self.hit return log_odds, outline
[docs] def estimate_offset( positions: Sequence[tuple[float, float]], detections: Sequence[BaseGeometry], *, max_distance_m: float = 3.0, project: Project | None = None, ) -> tuple[float, float, int]: """ Shift that lines overhead detections up with objects placed from the street. Pairs every street position with the nearest detection center within ``max_distance_m`` (mutual nearest neighbors only) and takes the median of the differences, twice: the second pass searches half as far around the shifted detections. Use objects that do not move and that both sources place well (hydrants, poles, the same day's parked cars). Args: positions: Street-level object positions as ``(lon, lat)``. detections: Overhead outlines of the same class in longitude and latitude. max_distance_m: Farthest pairing in the first pass. project: ``(lon, lat) -> (x, y)`` in meters; one centered on the positions is made when omitted. Returns: tuple[float, float, int]: ``(east, north)`` in meters to add to the detections (pass it as :attr:`AerialEvidence.offset_m`) and the number of pairs it rests on (``0`` and no shift when none are found). Example: >>> from shapely.geometry import Point >>> from rapidtools.processing.street_localization import local_projection >>> project, unproject = local_projection(-117.4, 47.7) >>> street = [unproject(10.0 * i, 5.0) for i in range(6)] >>> aerial = [Point(*unproject(10.0 * i - 1.0, 5.5)).buffer(1e-5) ... for i in range(6)] >>> dx, dy, n = estimate_offset(street, aerial, project=project) >>> round(dx, 1), round(dy, 1), n (1.0, -0.5, 6) """ if not len(positions) or not len(detections): return 0.0, 0.0, 0 if project is None: from .street_localization import local_projection lon0 = float(np.mean([p[0] for p in positions])) lat0 = float(np.mean([p[1] for p in positions])) project, _ = local_projection(lon0, lat0) street = np.array([project(lon, lat) for lon, lat in positions]) aerial = np.array( [project(g.centroid.x, g.centroid.y) for g in detections if not g.is_empty] ) if not len(aerial): return 0.0, 0.0, 0 shift = np.zeros(2) n = 0 for reach in (max_distance_m, max_distance_m / 2.0): moved = aerial + shift d_sa, i_sa = cKDTree(moved).query(street, distance_upper_bound=reach) _, i_as = cKDTree(street).query(moved) pairs = [ (s, int(a)) for s, (d, a) in enumerate(zip(d_sa, i_sa, strict=True)) if math.isfinite(d) and int(i_as[int(a)]) == s ] if not pairs: break diff = np.array([street[s] - aerial[a] for s, a in pairs]) shift = np.median(diff, axis=0) n = len(pairs) if not n: return 0.0, 0.0, 0 return float(shift[0]), float(shift[1]), n
[docs] @dataclass class Registration: """ Where a street survey and an overhead image disagree, place by place. The positions of a street survey come from its receiver, those of an orthomosaic from its own georeferencing, and the two differ by a shift that changes slowly along the route: neighboring objects are off by much the same amount. Objects found in both sources are tie points. Each gives the shift at its place, and the shift anywhere is the median over the tie points around it, so a car that was parked again a meter away between the two captures does not move its neighbors. The tie points need not be of the class that is moved. Parked cars, seen well from the street and from above, register hydrants and anything else the same frames placed. An object is never moved by its own tie, only by those around it. Attributes: ties: ``(n, 2)`` positions of the tie points from the street survey, in local meters. shifts: ``(n, 2)`` street position minus image position at each. project: ``(lon, lat) -> (x, y)`` in those meters. unproject: Its inverse. radius_m: Tie points this close to a place tell its shift. min_ties: Fewest of them for a local shift. With fewer, twice the radius is searched, and failing that the shift of the whole survey (the median over all tie points) is used. Example: >>> from shapely.geometry import Point >>> from rapidtools.processing.street_localization import local_projection >>> project, unproject = local_projection(-117.4, 47.7) >>> street = [unproject(10.0 * i, 5.0) for i in range(8)] >>> image = [Point(*unproject(10.0 * i - 1.0, 5.5)).buffer(1e-5) ... for i in range(8)] >>> registration = Registration.from_detections(street, image) >>> east, north, n = registration.shift_at(*unproject(35.0, 5.0)) >>> round(east, 1), round(north, 1), n (1.0, -0.5, 8) """ ties: np.ndarray shifts: np.ndarray project: Project unproject: Callable[[float, float], tuple[float, float]] radius_m: float = 40.0 min_ties: int = 3 def __post_init__(self) -> None: self.ties = np.asarray(self.ties, float).reshape(-1, 2) self.shifts = np.asarray(self.shifts, float).reshape(-1, 2) self._tree = cKDTree(self.ties) if len(self.ties) else None self._overall = ( np.median(self.shifts, axis=0) if len(self.shifts) else np.zeros(2) )
[docs] @classmethod def from_detections( cls, positions: Sequence[tuple[float, float]], detections: Sequence[BaseGeometry], *, max_distance_m: float = 3.0, radius_m: float = 40.0, min_ties: int = 3, ) -> Registration: """ Pair street positions with overhead detections of the same class. The shift of the whole survey is found first (:func:`estimate_offset`); with it taken out, every street position whose nearest detection center lies within half of ``max_distance_m``, and is nearest to it in turn, is a tie point. Args: positions: Street-level object positions as ``(lon, lat)``. detections: Overhead outlines of the same class in longitude and latitude. max_distance_m: Farthest pairing while the overall shift is sought; ties are paired within half of it afterward. radius_m: See :class:`Registration`. min_ties: See :class:`Registration`. Returns: Registration: With no tie points when the two do not pair up; it then moves nothing. """ from .street_localization import local_projection if len(positions): lon0 = float(np.mean([p[0] for p in positions])) lat0 = float(np.mean([p[1] for p in positions])) else: lon0 = lat0 = 0.0 project, unproject = local_projection(lon0, lat0) empty = cls(np.zeros((0, 2)), np.zeros((0, 2)), project, unproject) empty.radius_m, empty.min_ties = radius_m, min_ties east, north, n = estimate_offset( positions, detections, max_distance_m=max_distance_m, project=project ) if not n: return empty street = np.array([project(lon, lat) for lon, lat in positions]) image = np.array( [project(g.centroid.x, g.centroid.y) for g in detections if not g.is_empty] ) moved = image + np.array([east, north]) reach = max_distance_m / 2.0 d_si, i_si = cKDTree(moved).query(street, distance_upper_bound=reach) _, i_is = cKDTree(street).query(moved) pairs = [ (s, int(a)) for s, (d, a) in enumerate(zip(d_si, i_si, strict=True)) if math.isfinite(d) and int(i_is[int(a)]) == s ] return cls( np.array([street[s] for s, _ in pairs]), np.array([street[s] - image[a] for s, a in pairs]), project, unproject, radius_m, min_ties, )
[docs] def shift_at(self, lon: float, lat: float) -> tuple[float, float, int]: """ Shift of the street survey against the image at one place. A tie point at the place itself (within a quarter meter) is left out, so an object is not moved onto its own overhead outline. Returns: tuple[float, float, int]: ``(east, north)`` in meters, street minus image, and the number of tie points it rests on (all of them when the overall shift had to be used, ``0`` when there are none). """ if self._tree is None: return 0.0, 0.0, 0 at = np.array(self.project(lon, lat)) for radius in (self.radius_m, 2.0 * self.radius_m): near = [ k for k in self._tree.query_ball_point(at, radius) if math.hypot(*(self.ties[k] - at)) > 0.25 ] if len(near) >= self.min_ties: east, north = np.median(self.shifts[near], axis=0) return float(east), float(north), len(near) return float(self._overall[0]), float(self._overall[1]), len(self.ties)
[docs] def to_image( self, geometry: BaseGeometry ) -> tuple[BaseGeometry, float, float, int]: """ Move a geometry placed from the street to where the image has it. Returns: tuple: The moved geometry (longitude and latitude), the ``(east, north)`` shift in meters that was taken off, and the number of tie points behind it. """ center = geometry.centroid east, north, n = self.shift_at(center.x, center.y) if not n: return geometry, 0.0, 0.0, 0 x, y = self.project(center.x, center.y) lon, lat = self.unproject(x - east, y - north) dlon, dlat = lon - center.x, lat - center.y moved = shapely_transform( lambda px, py, pz=None: (px + dlon, py + dlat), geometry ) return moved, east, north, n
[docs] def register_to_image( assets: Any, detections: Sequence[BaseGeometry], *, tie_class: str | None = None, max_distance_m: float = 3.0, radius_m: float = 40.0, min_ties: int = 3, ) -> Registration: """ Move objects placed from the street onto an overhead image's positions. The assets of ``tie_class`` (all of them when ``None``) are paired with ``detections`` of the same class in the image; what the pairs around a place agree on is the survey's shift there (see :class:`Registration`), and every asset is moved by the shift at its own place. Each moved asset records the shift in ``registration_shift_m`` (east and north, street minus image) and the number of tie points in ``registration_ties``. This is a step of its own, after detection: the street survey needs no image to place its objects, and an image taken later can still be used to line them up with it. Args: assets: A :class:`~rapidtools.core.PhysicalAssetCollection` (or any iterable of assets with a ``geometry`` and ``attributes``) from the street survey; modified in place. detections: Overhead outlines of ``tie_class`` in longitude and latitude. tie_class: ``asset_type`` of the assets to pair with the detections, such as ``'vehicles'``. max_distance_m: Farthest pairing while the overall shift is sought. radius_m: Tie points this close to an asset tell its shift. min_ties: Fewest of them for a local shift. Returns: Registration: The registration that was applied; it has no ties, and nothing was moved, when the two sources do not pair up. Example: >>> registration = register_to_image( # doctest: +SKIP ... street_assets, car_outlines, tie_class='vehicles') >>> len(registration.ties) # doctest: +SKIP 212 """ members = list(assets) ties = [ a for a in members if tie_class is None or a.attributes.get('asset_type') == tie_class ] registration = Registration.from_detections( [(a.geometry.centroid.x, a.geometry.centroid.y) for a in ties], detections, max_distance_m=max_distance_m, radius_m=radius_m, min_ties=min_ties, ) if not len(registration.ties): return registration for asset in members: moved, east, north, n = registration.to_image(asset.geometry) asset.geometry = moved asset.attributes['registration_shift_m'] = [round(east, 2), round(north, 2)] asset.attributes['registration_ties'] = n return registration