Source code for openworld_radio_twin.simulation.antenna_placement

"""Place antenna records in a compiled scene as Sionna-ready transmitters.

Every interface (the Python loader, the web service, dataset generation and the built-in
Sionna engine) places antennas through this module, so a transmitter taken from a source
has the same position and orientation wherever it is used.
"""

from __future__ import annotations

import math
from collections import Counter
from dataclasses import replace

from shapely import STRtree
from shapely.geometry import Point, Polygon

from openworld_radio_twin.geodesy import LocalFrame
from openworld_radio_twin.models import AntennaDefaults, AntennaFeature
from openworld_radio_twin.providers.base import AntennaQueryResult
from openworld_radio_twin.simulation.scene_builder import (
    LocalBuilding,
    SceneAssets,
    terrain_elevation,
)

# Values placement completes, with the words its warnings use for them.
DEFAULTED_VALUES = {
    "height_agl_m": "height",
    "azimuth_deg": "azimuth",
    "downtilt_deg": "downtilt",
    "power_dbm": "power",
}


[docs] def sionna_orientation(azimuth_deg: float, downtilt_deg: float) -> tuple[float, float, float]: """Sionna's rotation angles (alpha, beta, gamma) in radians for a compass bearing. Sionna rotates the antenna boresight to (cos a cos b, sin a cos b, -sin b) in the scene's east, north and up axes. A compass azimuth, clockwise from north, is therefore alpha = 90 degrees - azimuth, and a positive downtilt is beta. """ alpha = (90.0 - azimuth_deg + 180.0) % 360.0 - 180.0 return math.radians(alpha), math.radians(downtilt_deg), 0.0
class _Roofs: """Base and roof heights of the scene's buildings at a point, in scene coordinates.""" def __init__(self, buildings: tuple[LocalBuilding, ...]) -> None: self.buildings = buildings self.tree = STRtree( [Polygon(building.exterior, building.holes) for building in buildings] ) def at(self, east_m: float, north_m: float) -> tuple[float, float] | None: point = Point(east_m, north_m) hits = self.tree.query(point, predicate="intersects") if len(hits) == 0: return None containing = [self.buildings[index] for index in hits] return ( min(building.scene_minimum_height_m for building in containing), max(building.scene_roof_height_m for building in containing), ) def _sectors(record: AntennaFeature, defaults: AntennaDefaults) -> list[AntennaFeature]: if record.azimuth_deg is not None or not defaults.sectors: return [record] return [ record.model_copy( update={ "feature_id": f"{record.feature_id}#sector{index}", "azimuth_deg": float(azimuth), "basis": {**record.basis, "azimuth_deg": "default"}, } ) for index, azimuth in enumerate(defaults.sectors, start=1) ]
[docs] def keep_inside_square( result: AntennaQueryResult, longitude: float, latitude: float, radius_m: float ) -> AntennaQueryResult: """Keep the antennas inside the square around a centre and count the others.""" frame = LocalFrame.at(longitude, latitude) inside = [] for record in result.antennas: east, north, _ = frame.to_local(record.longitude, record.latitude) if max(abs(east), abs(north)) <= radius_m: inside.append(record) excluded = len(result.antennas) - len(inside) if not excluded: return result return replace( result, antennas=inside, warnings=[ *result.warnings, f"Excluded {excluded} antenna records outside the square scene; interference from " "sites beyond the scene boundary is not modelled.", ], boundary_excluded_count=result.boundary_excluded_count + excluded, )
[docs] def keep_inside_scene(result: AntennaQueryResult, assets: SceneAssets) -> AntennaQueryResult: """Keep the antennas inside a compiled scene's square and count the others.""" return keep_inside_square( result, assets.origin_longitude, assets.origin_latitude, assets.radius_m )
[docs] def complete_antennas( result: AntennaQueryResult, defaults: AntennaDefaults | None = None ) -> AntennaQueryResult: """Fill the values a source does not give and set each antenna's Sionna orientation. Values come from ``defaults`` and are marked ``default``; a value the source gives counts as ``source`` unless the provider marked it otherwise. This needs no scene, so a map can show antennas before one is compiled; :func:`place_antennas` adds the scene position. """ defaults = defaults or AntennaDefaults() completed: list[AntennaFeature] = [] filled: Counter[str] = Counter() for record in result.antennas: for antenna in _sectors(record, defaults): values = {name: getattr(antenna, name) for name in DEFAULTED_VALUES} basis = {"position": "source", **antenna.basis} if antenna.bands: basis.setdefault("bands", "source") for name, value in values.items(): if value is None: values[name] = getattr(defaults, name) basis[name] = "default" filled[name] += 1 else: basis.setdefault(name, "source") orientation = sionna_orientation(values["azimuth_deg"], values["downtilt_deg"]) completed.append( antenna.model_copy(update={**values, "basis": basis, "orientation": orientation}) ) warnings = list(result.warnings) if filled: described = ", ".join( f"{word} for {filled[name]}" for name, word in DEFAULTED_VALUES.items() if filled[name] ) warnings.append(f"Default values used where the source gives none: {described}.") return replace(result, antennas=completed, warnings=warnings)
[docs] def place_antennas( result: AntennaQueryResult, assets: SceneAssets, defaults: AntennaDefaults | None = None, ) -> AntennaQueryResult: """Keep antennas inside the scene square and complete them as Sionna transmitters. Values the source does not give come from ``defaults`` and are marked ``default``. An antenna that would sit inside a building of this scene is raised above its roof by ``defaults.roof_clearance_m`` and its height is marked ``adjusted``: register heights and building heights come from different sources, and a transmitter enclosed by a building shell would produce an empty radio map. """ defaults = defaults or AntennaDefaults() result = complete_antennas(keep_inside_scene(result, assets), defaults) frame = LocalFrame.at(assets.origin_longitude, assets.origin_latitude) roofs = _Roofs(assets.local_buildings) if assets.local_buildings else None placed: list[AntennaFeature] = [] raised = 0 for antenna in result.antennas: east, north, _ = frame.to_local(antenna.longitude, antenna.latitude) ground = terrain_elevation(assets, east, north) height = antenna.height_agl_m basis = dict(antenna.basis) roof = roofs.at(east, north) if roofs is not None else None if roof is not None: base, top = roof if base <= ground + height < top + defaults.roof_clearance_m: height = top + defaults.roof_clearance_m - ground basis["height_agl_m"] = "adjusted" raised += 1 placed.append( antenna.model_copy( update={ "height_agl_m": height, "basis": basis, "position": (east, north, ground + height), } ) ) warnings = list(result.warnings) if raised: warnings.append( f"Raised {raised} antennas that would sit inside a building to " f"{defaults.roof_clearance_m:g} m above its roof." ) return replace(result, antennas=placed, warnings=warnings)