Source code for rapidtools.processing.postprocessing.roads

# 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-28-2026

"""
Regularization of raster-derived road polygons into clean centerlines.

This module provides :class:`RoadwayRegularizer`, a pure-geometry pipeline
component that converts the jagged blobs produced by raster-to-vector road
segmentation (e.g., from
:class:`~rapidtools.processing.SAM3OrthoFeatureExtractor` with the prompt
``'road'``) into clean centerlines with statistically sampled widths, and
rebuilds non-overlapping road polygons from them. A road comes out
straight where its skeleton is straight and curved where it curves, and
the corners of an intersection are rounded where the input shows them so.

All computation happens in a local azimuthal-equidistant projection in US
survey feet; inputs and outputs are WGS84.

Example:
    >>> from rapidtools.core import PhysicalAssetCollection
    >>> from rapidtools.processing import RoadwayRegularizer
    >>> raw_roads = PhysicalAssetCollection.from_geojson('roads_raw.geojson')
    >>> centerlines, polygons = RoadwayRegularizer(min_width_ft=20)(raw_roads)
    >>> centerlines.to_geojson('centerlines.geojson')
    >>> polygons.to_geojson('roads_clean.geojson')
"""

import logging
import math
import statistics
import uuid
from typing import Any, Generic, Literal, TypeVar, cast, overload

import networkx as nx
import pyproj
import shapely
from shapely.geometry import LineString, MultiPoint
from shapely.geometry.base import BaseGeometry
from shapely.ops import linemerge, transform, unary_union, voronoi_diagram
from tqdm import tqdm

from rapidtools.core import PhysicalAsset, PhysicalAssetCollection
from rapidtools.processing.step import Stage

logger = logging.getLogger(__name__)

# What ``RoadwayRegularizer.__call__`` returns: a ``(centerlines, polygons)``
# tuple for ``output='both'`` or a single collection otherwise.
_OutT = TypeVar('_OutT')
_Both = tuple[PhysicalAssetCollection, PhysicalAssetCollection]

ASSET_TYPE = 'road'

# Pipeline configuration constants:
# These constants define the heuristic thresholds and multipliers used by the
# geometry processing algorithms. They can be modified to tune the regularization
# behavior for different scales of assets (e.g., highways vs. alleyways).

# 1. Loading & Initial Processing
MIN_POLYGON_AREA_SQFT = 1000.0  # Ignore stray artifacts smaller than this
CLEANUP_BUFFER_FT = 0.1  # Buffer used to fuse slightly disconnected polygons
MIN_APPROX_WIDTH_FT = 10.0  # Absolute baseline width fallback for roads

# 2. Skeletonization Parameters (Multipliers of calculated approx_width)
SKELETON_SIMPLIFY_FACTOR = 0.1  # Initial smoothing tolerance
SKELETON_BUFFER_FACTOR = 0.2  # Outward/Inward buffer to remove jagged edges
SKELETON_SEGMENTIZE_FACTOR = 0.5  # Distance between points injected along boundary
SKELETON_CLIP_FACTOR = 0.05  # Negative buffer to clip Voronoi lines inside polygon
SKELETON_SNAP_GRID_FT = 0.001  # Grid used to snap Voronoi edge endpoints before merging

# 3. Graph Healing & Pruning
COORD_ROUNDING_DECIMALS = 1  # Precision used when identifying graph nodes
DEAD_END_PRUNING_FACTOR = 2.5  # Multiplier of approx_width to identify stub dead-ends

# 4. Centerline Fitting (multipliers of calculated approx_width)
JUNCTION_MERGE_FACTOR = 1.0  # Junctions joined by an edge shorter than this are one
JUNCTION_TRIM_FACTOR = 1.0  # Skeleton this close to a junction hooks; it is left out
MAX_MERGE_ANGLE_DEG = 25.0  # Edges continue each other through a junction within this
DIRECTION_SPAN_FACTOR = 1.5  # Length of edge its heading beyond a junction is read on
CURVE_SAMPLE_FACTOR = 0.25  # Spacing of the points a centerline is fitted to
CURVE_SMOOTHING_FACTOR = 0.75  # Gaussian sigma that takes the wobble out of a skeleton
STRAIGHT_TOLERANCE_FACTOR = (
    0.2  # A road is straight if it stays this close to its chord
)
CURVE_SIMPLIFY_FACTOR = 0.02  # Vertex tolerance of a curved centerline
MIN_SEGMENT_LENGTH_FT = 1.0  # Drop centerlines shorter than this

# 4b. Rounded Corners at Intersections
CORNER_RADIUS_FACTORS = (1.0, 0.75, 0.5, 0.35, 0.25)  # Radii tried, x narrower road
CORNER_MIN_FIT = 0.8  # Share of a rounded corner that must lie on the input surface
CORNER_REACH_FACTOR = 3.0  # Neighborhood of a junction worked on, x wider road
JUNCTION_TOUCH_FT = 0.01  # Centerlines this close to each other meet

# 5. Statistical Width Sampling
MIN_SAMPLES_PER_SEGMENT = 3  # Min width measurements per road segment
SAMPLE_SPACING_FACTOR = 0.5  # Spacing between samples (multiplier of approx_width)
DERIVATIVE_DELTA_FT = 1.0  # Delta offset used to calculate the normal vector (heading)
MEASURING_TAPE_FACTOR = 5.0  # Multiplier of approx_width defining max sampling ray cast

# 6. Output Formatting
OUTPUT_ROUNDING_DECIMALS = 2  # Decimals used when storing properties (width, azimuth)


def _smooth_pinned(values: list[float], sigma: float) -> list[float]:
    """
    Gaussian smoothing of a sequence that leaves its two ends where they are.

    The sequence is continued past each end by its mirror image through the
    end value, which makes the weighted mean at the end the end value itself.

    Example:
        >>> out = _smooth_pinned([0.0, 0.0, 1.0, 0.0, 0.0], 1.0)
        >>> out[0], out[-1], 0.3 < out[2] < 0.5
        (0.0, 0.0, True)
    """
    n = len(values)
    if n < 3 or sigma <= 0:
        return list(values)
    reach = min(n - 1, max(1, int(math.ceil(3.0 * sigma))))
    weights = [math.exp(-0.5 * (k / sigma) ** 2) for k in range(-reach, reach + 1)]
    total = sum(weights)
    first, last = values[0], values[-1]
    padded = (
        [2.0 * first - values[k] for k in range(reach, 0, -1)]
        + list(values)
        + [2.0 * last - values[n - 1 - k] for k in range(1, reach + 1)]
    )
    return [
        sum(w * padded[i + k] for k, w in enumerate(weights)) / total for i in range(n)
    ]


[docs] class RoadwayRegularizer(Generic[_OutT]): """ Pipeline component to regularize jagged raster-to-vector road polygons. This regularizer processes raw input geometries, extracts a Voronoi-based centerline skeleton, heals the graph, merges collinear segments, and statistically samples widths. It outputs in-memory ``PhysicalAssetCollection`` objects for both the centerlines and the reconstructed polygons. Args: min_width_ft (float, optional): The minimum enforced width for any regularized road segment in feet. Defaults to 22.0. min_network_length_ft (float, optional): The minimum cumulative length a connected skeleton component must possess to be considered a valid road network. Any disconnected stub networks shorter than this value will be filtered out. Defaults to 100.0. Example: >>> from rapidtools.core import PhysicalAssetCollection >>> from rapidtools.processing import RoadwayRegularizer >>> >>> raw = PhysicalAssetCollection.from_geojson('roads_raw.geojson') >>> regularizer = RoadwayRegularizer( ... min_width_ft=22.0, min_network_length_ft=150.0 ... ) >>> centerlines, polygons = regularizer(raw) >>> centerlines[0].attributes {'asset_type': 'road_centerline', 'width_ft': 24.5, 'azimuth_deg': 91.2} """ stage = Stage.REGULARIZE @overload def __init__( self: 'RoadwayRegularizer[_Both]', min_width_ft: float = ..., min_network_length_ft: float = ..., output: Literal['both'] = ..., ) -> None: ... @overload def __init__( self: 'RoadwayRegularizer[PhysicalAssetCollection]', min_width_ft: float = ..., min_network_length_ft: float = ..., *, output: Literal['polygons', 'centerlines'], ) -> None: ... @overload def __init__( self: 'RoadwayRegularizer[Any]', min_width_ft: float = ..., min_network_length_ft: float = ..., output: str = ..., ) -> None: ... def __init__( self, min_width_ft: float = 22.0, min_network_length_ft: float = 100.0, output: str = 'both', ): """ Initialize the regularizer thresholds. Args: min_width_ft (float, optional): Minimum enforced road width in feet. min_network_length_ft (float, optional): Minimum cumulative length of a skeleton component in feet. """ self.min_width_ft = min_width_ft self.min_network_length_ft = min_network_length_ft if output not in ('both', 'polygons', 'centerlines'): raise ValueError( f"output must be 'both', 'polygons' or 'centerlines', got {output!r}." ) # 'both' returns (centerlines, polygons); the single-collection modes make # the regularizer usable as a Pipeline step. self.output = output def __call__(self, input_assets: PhysicalAssetCollection) -> _OutT: """ Allow the instance to be called directly like a function. Args: input_assets (PhysicalAssetCollection): The raw input road polygons (WGS84). Returns: With ``output='both'`` (the default), a tuple containing the centerlines collection and the reconstructed polygons collection; with ``output='polygons'`` or ``output='centerlines'``, just that collection. Example: >>> centerlines, polygons = RoadwayRegularizer()(raw_roads) """ centerlines, polygons = self.process(input_assets) # The casts are backed by the ``__init__`` overloads, which tie # ``_OutT`` to the ``output`` mode: if self.output == 'polygons': return cast(_OutT, polygons) if self.output == 'centerlines': return cast(_OutT, centerlines) return cast(_OutT, (centerlines, polygons))
[docs] def process( self, input_assets: PhysicalAssetCollection ) -> tuple[PhysicalAssetCollection, PhysicalAssetCollection]: """ Execute the regularization logic and return asset collections. The steps are: project to a local feet-based CRS, drop polygons smaller than ``MIN_POLYGON_AREA_SQFT``, fuse near-touching polygons, skeletonize with a Voronoi diagram, heal/prune the skeleton graph, remove short stub networks, chain the edges that continue each other and fit a centerline to each chain (straight where the skeleton is, curved where it curves), sample widths and azimuths, and finally rebuild WGS84 centerline and polygon assets, with the corners of intersections rounded where the input shows them rounded. Args: input_assets (PhysicalAssetCollection): The raw input road polygons (WGS84). Returns: tuple[PhysicalAssetCollection, PhysicalAssetCollection]: A tuple containing: - ``centerlines_collection``: Assets representing the road centerlines (``LineString`` geometries) with the attributes ``'asset_type': 'road_centerline'``, ``'width_ft'`` and ``'azimuth_deg'``. - ``polygons_collection``: Assets representing the regularized polygons with ``'asset_type': 'road_polygon'`` and the same width/azimuth attributes. Both collections are empty when the input is empty or when no polygon exceeds the minimum area. Example: >>> centerlines, polygons = RoadwayRegularizer().process(raw_roads) >>> polygons[0].attributes['asset_type'] 'road_polygon' """ logger.info('Starting Roadway Regularization Pipeline...') # 1. Extract Geometries & Project raw_geometries = [asset.geometry for asset in input_assets] if not raw_geometries: logger.warning('No valid geometries found in input collection. Exiting.') return PhysicalAssetCollection(), PhysicalAssetCollection() union_all = unary_union(raw_geometries) project_to_feet, project_to_wgs84 = self._get_transformers(union_all) valid_polys = [ transform(project_to_feet, g).buffer(0) for g in raw_geometries if transform(project_to_feet, g).area > MIN_POLYGON_AREA_SQFT ] if not valid_polys: logger.warning( f'No input polygon exceeds {MIN_POLYGON_AREA_SQFT} sq ft. Exiting.' ) return PhysicalAssetCollection(), PhysicalAssetCollection() all_networks = unary_union( [ p.buffer(CLEANUP_BUFFER_FT, join_style=2).buffer( -CLEANUP_BUFFER_FT, join_style=2 ) for p in valid_polys ] ) largest_poly = self._get_largest_polygon(all_networks) approx_width = max( MIN_APPROX_WIDTH_FT, 2.0 * (largest_poly.area / largest_poly.length) ) # 2. Skeletonization merged_lines = self._generate_voronoi_skeleton(all_networks, approx_width) # 3. Graph Healing & Pruning graph = self._build_and_heal_graph(merged_lines, approx_width) # 4. Filter Stub Networks graph = self._filter_stub_networks(graph, approx_width) # 5. Chain Edges Through Junctions & Fit Centerlines straight_segments = self._merge_collinear_segments( graph, approx_width, all_networks ) # 6. Sample Widths & Azimuth analyzed_segments = self._calculate_widths_and_azimuths( straight_segments, all_networks, approx_width ) # 7. Build Centerlines Collection centerlines_collection = self._build_centerlines_collection( analyzed_segments, project_to_wgs84 ) # 8. Reconstruct Polygons & Build Collection polygons_collection = self._build_polygons_collection( analyzed_segments, project_to_wgs84, all_networks ) # 9. Default undefined asset types to 'road' centerlines_collection.set_asset_type(ASSET_TYPE, overwrite=False) polygons_collection.set_asset_type(ASSET_TYPE, overwrite=False) logger.info('Roadway regularization complete.') return centerlines_collection, polygons_collection
# --- Private Helper Methods --- def _get_geoms(self, geometry: BaseGeometry) -> list[BaseGeometry]: """ Extract the list of sub-geometries from a (multi-part) geometry. Args: geometry (BaseGeometry): Any Shapely geometry. Returns: list[BaseGeometry]: The parts of a multi-part geometry, or ``[geometry]`` for a single-part geometry. """ if hasattr(geometry, 'geoms'): return list(geometry.geoms) return [geometry] def _get_lines(self, geom: BaseGeometry) -> list[LineString]: """ Recursively extract ``LineString`` parts from a geometry. Args: geom (BaseGeometry): A ``LineString``, ``MultiLineString`` or nested ``GeometryCollection``. Returns: list[LineString]: All ``LineString`` parts found (empty for point/polygon input). """ lines = [] if geom.geom_type == 'LineString': lines.append(geom) elif hasattr(geom, 'geoms'): for part in geom.geoms: lines.extend(self._get_lines(part)) return lines def _get_transformers(self, base_geom: BaseGeometry) -> tuple[Any, Any]: """ Build pyproj transformers between WGS84 and a local feet-based CRS. The local CRS is an azimuthal equidistant projection centered on the centroid of ``base_geom`` with units of US survey feet. Args: base_geom (BaseGeometry): WGS84 geometry whose centroid defines the projection origin. Returns: tuple[Callable, Callable]: ``(project_to_feet, project_to_wgs84)`` transform functions suitable for :func:`shapely.ops.transform`. """ proj_wgs84 = pyproj.CRS('EPSG:4326') proj_feet = pyproj.CRS( f'+proj=aeqd +lat_0={base_geom.centroid.y} ' f'+lon_0={base_geom.centroid.x} +datum=WGS84 +units=us-ft' ) project_to_feet = pyproj.Transformer.from_crs( proj_wgs84, proj_feet, always_xy=True ).transform project_to_wgs84 = pyproj.Transformer.from_crs( proj_feet, proj_wgs84, always_xy=True ).transform return project_to_feet, project_to_wgs84 def _get_largest_polygon(self, geom: BaseGeometry) -> BaseGeometry: """ Find the largest single polygon within a multi-part geometry. Args: geom (BaseGeometry): A ``Polygon``, ``MultiPolygon`` or ``GeometryCollection``. Returns: BaseGeometry: The polygon part with the largest area, or ``geom`` itself when it is not multi-part. """ if geom.geom_type in ['MultiPolygon', 'GeometryCollection']: return max( [g for g in self._get_geoms(geom) if g.geom_type == 'Polygon'], key=lambda p: p.area, ) return geom def _extract_all_coords(self, geom: BaseGeometry) -> list[tuple[float, float]]: """ Recursively extract coordinate tuples from a geometry. Args: geom (BaseGeometry): Any geometry; multi-part geometries are flattened. Returns: list[tuple[float, float]]: All coordinates found, in order. Objects with neither ``geoms`` nor ``coords`` yield an empty list. """ if hasattr(geom, 'geoms'): pts = [] for g in geom.geoms: pts.extend(self._extract_all_coords(g)) return pts elif hasattr(geom, 'coords'): return list(geom.coords) return [] def _generate_voronoi_skeleton( self, network_geom: BaseGeometry, approx_width: float ) -> BaseGeometry: """ Generate a centerline skeleton from road polygons using a Voronoi diagram. The polygon is smoothed, its boundary densified, and the Voronoi edges of the boundary points are clipped to the polygon interior. Edges that remain form the medial axis approximation. Edge endpoints are snapped to ``SKELETON_SNAP_GRID_FT`` so that adjoining edges merge cleanly. Args: network_geom (BaseGeometry): The fused road polygons in the local feet CRS. approx_width (float): Estimated road width in feet; scales all tolerances. Returns: BaseGeometry: A ``LineString`` or ``MultiLineString`` of merged skeleton edges. """ logger.info('Generating Voronoi skeleton...') smoothed_poly = ( network_geom.simplify(approx_width * SKELETON_SIMPLIFY_FACTOR) .buffer(approx_width * SKELETON_BUFFER_FACTOR, join_style=2) .buffer(-approx_width * SKELETON_BUFFER_FACTOR, join_style=2) ) boundary_pts = smoothed_poly.boundary.segmentize( approx_width * SKELETON_SEGMENTIZE_FACTOR ) coords = self._extract_all_coords(boundary_pts) voronoi_edges = voronoi_diagram(MultiPoint(coords), edges=True) clipped_lines = voronoi_edges.intersection( smoothed_poly.buffer(-approx_width * SKELETON_CLIP_FACTOR) ) # Voronoi edge endpoints computed from different cells can differ by # floating-point noise; snap them to a fine grid so that linemerge # recognizes them as shared vertices and produces continuous lines. snapped_lines = shapely.set_precision( unary_union(clipped_lines), SKELETON_SNAP_GRID_FT ) return linemerge(snapped_lines) def _build_and_heal_graph( self, merged_lines: BaseGeometry, approx_width: float ) -> nx.Graph: """ Build a NetworkX graph from skeleton lines and prune or heal segments. Nodes are line endpoints rounded to ``COORD_ROUNDING_DECIMALS``; the line vertices are snapped onto those node coordinates so edges join exactly. Edges carry ``geom`` and ``length`` attributes. Degree-2 nodes are collapsed by merging their two edges, and dead-end edges shorter than ``approx_width * DEAD_END_PRUNING_FACTOR`` are removed. The two operations alternate until the graph stops changing. Args: merged_lines (BaseGeometry): Skeleton lines from :meth:`_generate_voronoi_skeleton`. approx_width (float): Estimated road width in feet. Returns: nx.Graph: The healed and pruned skeleton graph. """ logger.info('Building and healing graph...') G = nx.Graph() # Build initial graph for line in self._get_geoms(merged_lines): if line.geom_type != 'LineString': continue start = ( round(line.coords[0][0], COORD_ROUNDING_DECIMALS), round(line.coords[0][1], COORD_ROUNDING_DECIMALS), ) end = ( round(line.coords[-1][0], COORD_ROUNDING_DECIMALS), round(line.coords[-1][1], COORD_ROUNDING_DECIMALS), ) if start != end: # Snap the line's end vertices onto the rounded node keys so # that every edge meeting at a node shares exactly the same # coordinate; otherwise linemerge cannot fuse them when the # node is healed below. coords = list(line.coords) coords[0] = start coords[-1] = end line = LineString(coords) G.add_edge(start, end, geom=line, length=line.length) # Heal and Prune pruning = True while pruning: pruning = False healing = True while healing: healing = False deg2_nodes = [n for n in G.nodes if G.degree(n) == 2] for n in deg2_nodes: if G.degree(n) == 2: u, v = list(G.neighbors(n)) if u != v and not G.has_edge(u, v): lines_to_merge = self._get_lines( G[u][n]['geom'] ) + self._get_lines(G[n][v]['geom']) merged_geom = linemerge(lines_to_merge) new_length = G[u][n]['length'] + G[n][v]['length'] G.add_edge(u, v, geom=merged_geom, length=new_length) G.remove_node(n) healing = True dead_ends = [n for n in G.nodes if G.degree(n) == 1] for node in dead_ends: if G.has_node(node) and G.degree(node) == 1: neighbor = list(G.neighbors(node))[0] if ( G[node][neighbor]['length'] < approx_width * DEAD_END_PRUNING_FACTOR ): G.remove_node(node) pruning = True return G def _filter_stub_networks(self, G: nx.Graph, approx_width: float) -> nx.Graph: """ Remove connected components whose total length is too short. Args: G (nx.Graph): Skeleton graph with ``length`` edge attributes. approx_width (float): Estimated road width in feet (currently unused; kept for signature symmetry with the other graph helpers). Returns: nx.Graph: A new graph containing only the edges of components longer than ``min_network_length_ft``. """ logger.info('Structurally filtering stub networks...') valid_edges = [] for comp in list(nx.connected_components(G)): subgraph = G.subgraph(comp) total_length = sum( data['length'] for _, _, data in subgraph.edges(data=True) ) if total_length > self.min_network_length_ft: valid_edges.extend(subgraph.edges(data=True)) filtered_G = nx.Graph() filtered_G.add_edges_from(valid_edges) return filtered_G def _merge_collinear_segments( self, G: nx.Graph, approx_width: float, network: BaseGeometry | None = None ) -> list[LineString]: """ Turn the skeleton graph into one clean centerline per road. Edges that continue each other through a junction (a road through both would turn by less than ``MAX_MERGE_ANGLE_DEG`` there, see :meth:`_turn_through`) are chained into one road, so a street keeps its line across its side streets. Each chain is then fitted (:meth:`_fit_centerline`): a straight line where the skeleton stays close to its chord, and a smooth curve that follows it otherwise. Junctions closer together than ``JUNCTION_MERGE_FACTOR`` road widths (the two branch points a skeleton makes of a four-way crossing) count as one, and a road that ends at a junction another road runs through ends on that road's line. Args: G (nx.Graph): Healed skeleton graph with ``geom`` edge attributes. approx_width (float): Estimated road width in feet. network (BaseGeometry | None): The road surface the skeleton came from. With it, the stretch of skeleton left out around a junction is as long as the junction is wide (twice the distance from its branch point to the edge of the surface): the wider the mouth of an intersection, the farther the skeleton is pulled into it. Without it, one road width is left out. Returns: list[LineString]: The fitted centerlines. """ logger.info('Fitting centerlines to the skeleton...') edges, junctions = self._contracted_edges(G, approx_width) if not edges: return [] edge_of_surface = network.boundary if network is not None else None reach = { node: JUNCTION_TRIM_FACTOR * max( approx_width, 2.0 * edge_of_surface.distance(shapely.Point(node)) if edge_of_surface is not None else 0.0, ) for node in junctions } # Which edge ends meet at each node, and where each end heads. ends_at: dict[tuple[float, float], list[tuple[int, int]]] = {} for k, (u, v, _) in enumerate(edges): ends_at.setdefault(u, []).append((k, 0)) ends_at.setdefault(v, []).append((k, 1)) partner: dict[tuple[int, int], tuple[int, int]] = {} for ends in ends_at.values(): if len(ends) < 2: continue node = edges[ends[0][0]][ends[0][1]] trim = reach.get(node, JUNCTION_TRIM_FACTOR * approx_width) pairs = [] for a in range(len(ends)): for b in range(a + 1, len(ends)): if ends[a][0] == ends[b][0]: continue # the two ends of a loop turn = self._turn_through( (edges[ends[a][0]][2], ends[a][1], trim), (edges[ends[b][0]][2], ends[b][1], trim), approx_width, ) pairs.append((turn, ends[a], ends[b])) for turn, one, other in sorted(pairs): if ( turn < MAX_MERGE_ANGLE_DEG and one not in partner and other not in partner ): partner[one], partner[other] = other, one # Follow the pairings from every free end; what is left are rings. chains: list[list[tuple[int, int]]] = [] used: set[int] = set() def follow(k: int, entry: int) -> list[tuple[int, int]]: chain = [] while k not in used: used.add(k) chain.append((k, entry)) nxt = partner.get((k, 1 - entry)) if nxt is None: break k, entry = nxt return chain for k in range(len(edges)): for entry in (0, 1): if k not in used and (k, entry) not in partner: chains.append(follow(k, entry)) for k in range(len(edges)): if k not in used: chains.append(follow(k, 0)) fitted: list[tuple[LineString, list[tuple[float, float]]]] = [] through: dict[tuple[float, float], int] = {} for chain in chains: coords: list[tuple[float, float]] = [] # Where along the chain each inner junction lies, and its reach: inner: list[tuple[float, float]] = [] travelled = 0.0 for n, (k, entry) in enumerate(chain): u, v, line = edges[k] part = list(line.coords) if entry == 0 else list(line.coords)[::-1] if n: node = u if entry == 0 else v if node in junctions: inner.append((travelled, reach[node])) part = part[1:] coords.extend(part) travelled += line.length first = edges[chain[0][0]][chain[0][1]] last = edges[chain[-1][0]][1 - chain[-1][1]] if len(coords) < 2: continue fit = self._fit_centerline( LineString(coords), approx_width, trim_start=reach.get(first, 0.0), trim_end=reach.get(last, 0.0), inner_junctions=inner, ) if fit.length <= MIN_SEGMENT_LENGTH_FT: continue for k, entry in chain[1:]: node = edges[k][0] if entry == 0 else edges[k][1] through.setdefault(node, len(fitted)) fitted.append((fit, [first, last])) # A road that ends at a junction another road runs through ends on # that road's line, which no longer passes through the junction # point exactly. lines = [fit for fit, _ in fitted] for n, (fit, (first, last)) in enumerate(fitted): coords = list(fit.coords) for node, at in ((first, 0), (last, -1)): m = through.get(node) if m is None or m == n: continue target = lines[m] snapped = target.interpolate(target.project(shapely.Point(coords[at]))) coords[at] = (snapped.x, snapped.y) if LineString(coords).length > MIN_SEGMENT_LENGTH_FT: lines[n] = LineString(coords) return [line for line in lines if line.length > MIN_SEGMENT_LENGTH_FT] def _contracted_edges( self, G: nx.Graph, approx_width: float ) -> tuple[ list[tuple[tuple[float, float], tuple[float, float], LineString]], set[tuple[float, float]], ]: """ The graph's edges with junctions that lie close together made one. The skeleton of a four-way crossing has two branch points joined by a short edge. Junctions (nodes of degree three or more) joined by an edge shorter than ``JUNCTION_MERGE_FACTOR`` road widths become one node at their mean position, the edge between them is dropped, and the other edges are led to the new node. Returns: tuple: The edges as ``(start node, end node, line)`` and the set of junction nodes among their ends. """ degree = dict(G.degree()) group = {n: n for n in G.nodes} def find(n: Any) -> Any: while group[n] != n: group[n] = group[group[n]] n = group[n] return n limit = approx_width * JUNCTION_MERGE_FACTOR for u, v, data in G.edges(data=True): if degree[u] >= 3 and degree[v] >= 3 and data['length'] < limit: group[find(u)] = find(v) members: dict[Any, list[Any]] = {} for n in G.nodes: members.setdefault(find(n), []).append(n) place = {} for root, nodes in members.items(): x = sum(n[0] for n in nodes) / len(nodes) y = sum(n[1] for n in nodes) / len(nodes) place[root] = (x, y) if len(nodes) > 1 else root edges = [] for u, v, data in G.edges(data=True): ru, rv = find(u), find(v) if ru == rv and data['length'] < limit: continue # the short edge inside a crossing for line in self._get_lines(data['geom']): coords = list(line.coords) if len(coords) < 2: continue # The stored line may run either way between its nodes. if math.dist(coords[0], u) > math.dist(coords[0], v): coords = coords[::-1] coords[0], coords[-1] = place[ru], place[rv] edges.append((place[ru], place[rv], LineString(coords))) count: dict[tuple[float, float], int] = {} for u, v, _ in edges: count[u] = count.get(u, 0) + 1 count[v] = count.get(v, 0) + 1 return edges, {n for n, c in count.items() if c >= 3} @staticmethod def _turn_through( one: tuple[LineString, int, float], other: tuple[LineString, int, float], approx_width: float, ) -> float: """ How sharply a road would turn if two edges at a node were one road. Each edge is given with the end that lies at the node (``0`` or ``1``) and the reach of the junction there. The skeleton hooks toward a junction, so nothing within that reach is used: a point is taken on each edge where the reach ends, and another ``DIRECTION_SPAN_FACTOR`` road widths farther on. The road through the node would run along the first edge to its near point, across the junction to the near point of the second, and on along that edge; the larger of the two turns it makes on the way is returned, in degrees. A road that curves gently through a junction makes two small turns the same way, where reading one heading on each side would add them up. """ def points(edge: tuple[LineString, int, float]) -> tuple[Any, Any]: line, end, trim = edge length = line.length near = min(trim, 0.25 * length) far = min(near + DIRECTION_SPAN_FACTOR * approx_width, length) if end == 1: near, far = length - near, length - far return line.interpolate(near), line.interpolate(far) a1, a2 = points(one) b1, b2 = points(other) legs = [ math.atan2(a1.y - a2.y, a1.x - a2.x), math.atan2(b1.y - a1.y, b1.x - a1.x), math.atan2(b2.y - b1.y, b2.x - b1.x), ] turns = [ abs((legs[k + 1] - legs[k] + math.pi) % (2.0 * math.pi) - math.pi) for k in range(2) ] return math.degrees(max(turns)) def _fit_centerline( self, path: LineString, approx_width: float, trim_start: float = 0.0, trim_end: float = 0.0, inner_junctions: list[tuple[float, float]] | None = None, ) -> LineString: """ Fit a clean centerline to the skeleton of one road. The skeleton wobbles with the outline it came from and hooks toward the side road at every junction. Its points within the reach of a junction are left out, the rest is sampled evenly and smoothed along its length with a Gaussian of ``CURVE_SMOOTHING_FACTOR`` road widths, its two ends held in place. If the smoothed line stays within ``STRAIGHT_TOLERANCE_FACTOR`` road widths of the chord between its ends, the road is that chord. Otherwise it is the smoothed line: a curve that follows the road. Args: path (LineString): The skeleton of the road, end to end. approx_width (float): Estimated road width in feet. trim_start (float): Reach of the junction the road starts at; ``0`` when it starts at none. trim_end (float): Reach of the junction it ends at. inner_junctions (list[tuple[float, float]] | None): Distance along the path, and reach, of each junction it runs through. Returns: LineString: The centerline, from the first to the last point of ``path``. """ length = path.length step = max(CURVE_SAMPLE_FACTOR * approx_width, length / 2000.0) n = max(2, int(math.ceil(length / step)) + 1) stations = [k * length / (n - 1) for k in range(n)] hidden = [(d - trim, d + trim) for d, trim in (inner_junctions or [])] # An end is trimmed only where enough road is left beyond it. if trim_start and length > 3.0 * trim_start: hidden.append((0.0, trim_start)) if trim_end and length > 3.0 * trim_end: hidden.append((length - trim_end, length)) kept = [ d for d in stations if d in (0.0, length) or not any(lo < d < hi for lo, hi in hidden) ] if len(kept) < 3: return LineString([path.coords[0], path.coords[-1]]) points = [path.interpolate(d) for d in kept] # Sample the line through the kept points evenly again, so that the # stretch across a junction is smoothed like any other. bridged = LineString([(p.x, p.y) for p in points]) m = max(3, int(math.ceil(bridged.length / step)) + 1) xs = [0.0] * m ys = [0.0] * m for k in range(m): p = bridged.interpolate(k * bridged.length / (m - 1)) xs[k], ys[k] = p.x, p.y sigma = CURVE_SMOOTHING_FACTOR * approx_width / (bridged.length / (m - 1)) xs, ys = _smooth_pinned(xs, sigma), _smooth_pinned(ys, sigma) smooth = LineString(list(zip(xs, ys, strict=True))) chord = LineString([smooth.coords[0], smooth.coords[-1]]) if chord.length > 0 and all( chord.distance(shapely.Point(c)) < STRAIGHT_TOLERANCE_FACTOR * approx_width for c in smooth.coords ): return chord return smooth.simplify( CURVE_SIMPLIFY_FACTOR * approx_width, preserve_topology=False ) def _calculate_widths_and_azimuths( self, segments: list[LineString], network: BaseGeometry, approx_width: float ) -> list[dict[str, Any]]: """ Sample the physical width and heading of each segment against the network. At evenly spaced stations along a segment, a "measuring tape" line perpendicular to the local heading is intersected with the road polygon; the median intersection length (floored at ``min_width_ft``) is the segment width. The azimuth is the compass bearing (degrees clockwise from north) from the first to the last vertex. Args: segments (list[LineString]): Straight centerline segments in the local feet CRS. network (BaseGeometry): The fused road polygons in the same CRS. approx_width (float): Estimated road width in feet; sets sample spacing and tape length. Returns: list[dict[str, Any]]: One dict per segment with keys ``'geometry'``, ``'width'`` (feet) and ``'azimuth'`` (degrees). """ logger.info('Statistically sampling road widths & calculating azimuth...') analyzed = [] for seg in tqdm(segments, desc=' -> Sampling'): length = seg.length num_samples = max( MIN_SAMPLES_PER_SEGMENT, int(length / (approx_width * SAMPLE_SPACING_FACTOR)), ) sampled_widths = [] for i in range(1, num_samples): dist = i * length / num_samples pt = seg.interpolate(dist) pt1 = seg.interpolate(max(0, dist - DERIVATIVE_DELTA_FT)) pt2 = seg.interpolate(min(length, dist + DERIVATIVE_DELTA_FT)) dx, dy = pt2.x - pt1.x, pt2.y - pt1.y norm = math.hypot(dx, dy) if norm == 0: continue nx_vec, ny_vec = -dy / norm, dx / norm measuring_tape = LineString( [ ( pt.x + nx_vec * approx_width * MEASURING_TAPE_FACTOR, pt.y + ny_vec * approx_width * MEASURING_TAPE_FACTOR, ), ( pt.x - nx_vec * approx_width * MEASURING_TAPE_FACTOR, pt.y - ny_vec * approx_width * MEASURING_TAPE_FACTOR, ), ] ) sampled_widths.append(measuring_tape.intersection(network).length) final_width = max( self.min_width_ft, statistics.median(sampled_widths) if sampled_widths else self.min_width_ft, ) coords = list(seg.coords) seg_dx, seg_dy = coords[-1][0] - coords[0][0], coords[-1][1] - coords[0][1] azimuth = (math.degrees(math.atan2(seg_dx, seg_dy)) + 360) % 360 analyzed.append({'geometry': seg, 'width': final_width, 'azimuth': azimuth}) return analyzed def _build_centerlines_collection( self, analyzed_segments: list[dict[str, Any]], proj_transform: Any ) -> PhysicalAssetCollection: """ Convert analyzed LineStrings into a WGS84 ``PhysicalAssetCollection``. Args: analyzed_segments (list[dict[str, Any]]): Data generated by :meth:`_calculate_widths_and_azimuths` containing geometry, width, and azimuth. proj_transform (Any): A pyproj transform function from the local CRS to WGS84. Returns: PhysicalAssetCollection: The resulting centerline assets (IDs ``'cl_<hash>'``). """ logger.info('Building centerlines PhysicalAssetCollection...') collection = PhysicalAssetCollection() for item in analyzed_segments: seg_wgs84 = transform(proj_transform, item['geometry']) for part in self._get_geoms(seg_wgs84): if part.geom_type == 'LineString' and not part.is_empty: asset = PhysicalAsset( id=f'cl_{uuid.uuid4().hex[:8]}', geometry=part, attributes={ 'asset_type': 'road_centerline', 'width_ft': round(item['width'], OUTPUT_ROUNDING_DECIMALS), 'azimuth_deg': round( item['azimuth'], OUTPUT_ROUNDING_DECIMALS ), }, ) collection.add(asset) return collection def _build_polygons_collection( self, analyzed_segments: list[dict[str, Any]], proj_transform: Any, network: BaseGeometry | None = None, ) -> PhysicalAssetCollection: """ Reconstruct non-overlapping road polygons from analyzed centerlines. Segments are buffered by half their width (flat caps) from widest to narrowest; each new polygon has all previously placed polygons subtracted so that intersections are owned by the wider road. Where roads meet, the corners between them are then rounded as far as the input surface is (:meth:`_rounded_corners`). Args: analyzed_segments (list[dict[str, Any]]): Data generated by :meth:`_calculate_widths_and_azimuths` containing geometry, width, and azimuth. Sorted in place by width (descending). proj_transform (Any): A pyproj transform function from the local CRS to WGS84. network (BaseGeometry | None): The input road surface in the local CRS. Corners are rounded only when it is given: it is what says how round they are. Returns: PhysicalAssetCollection: The resulting polygon assets (IDs ``'poly_<hash>'``). """ logger.info( 'Reconstructing linear polygons and building PhysicalAssetCollection...' ) analyzed_segments.sort(key=lambda x: x['width'], reverse=True) collection = PhysicalAssetCollection() placed: list[tuple[BaseGeometry, dict[str, Any]]] = [] for item in analyzed_segments: poly = item['geometry'].buffer(item['width'] / 2.0, cap_style=2) for p, _ in placed: p_bounds, poly_bounds = p.bounds, poly.bounds if not ( poly_bounds[2] < p_bounds[0] or poly_bounds[0] > p_bounds[2] or poly_bounds[3] < p_bounds[1] or poly_bounds[1] > p_bounds[3] ): if poly.intersects(p): poly = poly.difference(p) if poly.is_empty: break if not poly.is_empty: placed.append((poly, item)) if network is not None: placed = self._rounded_corners(placed, network) for poly, item in placed: for part in self._get_geoms(transform(proj_transform, poly)): if part.geom_type == 'Polygon' and not part.is_empty: asset = PhysicalAsset( id=f'poly_{uuid.uuid4().hex[:8]}', geometry=part, attributes={ 'asset_type': 'road_polygon', 'width_ft': round(item['width'], OUTPUT_ROUNDING_DECIMALS), 'azimuth_deg': round( item['azimuth'], OUTPUT_ROUNDING_DECIMALS ), }, ) collection.add(asset) return collection def _rounded_corners( self, placed: list[tuple[BaseGeometry, dict[str, Any]]], network: BaseGeometry, ) -> list[tuple[BaseGeometry, dict[str, Any]]]: """ Round the corners between roads that meet, as far as the input does. Two strips that meet leave a sharp inside corner, where the pavement of an intersection is rounded. Closing the strips around a junction with a disk of radius ``r`` fills each inside corner with the piece an arc of that radius cuts off. For every corner the largest radius of ``CORNER_RADIUS_FACTORS`` (times the width of the narrower road at the junction) is taken whose piece lies on the input surface by at least ``CORNER_MIN_FIT``; a corner the input shows square stays square. Each piece is joined to the road polygon it borders most. Args: placed (list[tuple[BaseGeometry, dict[str, Any]]]): The road polygons with their segments, in the local CRS. network (BaseGeometry): The input road surface in the same CRS. Returns: list[tuple[BaseGeometry, dict[str, Any]]]: The polygons with the rounded corners added. """ lines = [item['geometry'] for _, item in placed] polys = [poly for poly, _ in placed] tree = shapely.STRtree(lines) junctions: list[tuple[shapely.Point, float, float]] = [] for a, line in enumerate(lines): near = tree.query(line, predicate='dwithin', distance=JUNCTION_TOUCH_FT) for b in sorted(int(k) for k in near): if b <= a: continue meet = line.intersection(lines[b]) if meet.is_empty: # The end of a side road is put on the road it meets by # projection, which lands on that line only to float # precision: the two need not intersect exactly. meet = shapely.Point( shapely.shortest_line(line, lines[b]).coords[0] ) widths = sorted((placed[a][1]['width'], placed[b][1]['width'])) for point in self._get_geoms(meet): at = point if point.geom_type == 'Point' else point.centroid if all(at.distance(j[0]) > widths[0] for j in junctions): junctions.append((at, widths[0], widths[1])) if not junctions: return placed surface = unary_union(polys) for at, narrow, wide in junctions: reach = CORNER_REACH_FACTOR * wide around = at.buffer(reach) local = surface.intersection(around) taken: list[BaseGeometry] = [] for factor in CORNER_RADIUS_FACTORS: r = factor * narrow closed = local.buffer(r).buffer(-r) # Away from the cut edge of the neighborhood, which the # closing rounds as well. pieces = closed.difference(local).intersection( at.buffer(reach - 1.5 * r) ) for piece in self._get_geoms(pieces): if piece.geom_type != 'Polygon' or piece.area < 1.0: continue if any(piece.intersects(t) for t in taken): continue # this corner already has a larger radius if piece.intersection(network).area < CORNER_MIN_FIT * piece.area: continue taken.append(piece) for piece in taken: grown = piece.buffer(0.1) owner = max( range(len(polys)), key=lambda k: grown.intersection(polys[k]).area ) polys[owner] = polys[owner].union(grown).buffer(0) return [(poly, item) for poly, (_, item) in zip(polys, placed, strict=True)]