Source code for openworld_radio_twin.simulation.building_grid

import zipfile
import zlib
from pathlib import Path

import numpy as np

from openworld_radio_twin.conventions import (
    BUILDING_MASK_DTYPE,
    BUILDING_RASTERS_SUFFIX,
    BUILDING_ROOF_DTYPE,
)
from openworld_radio_twin.environment import EnvironmentData
from openworld_radio_twin.models import BuildingFeature, GridMapping
from openworld_radio_twin.simulation.scene_builder import (
    MeasurementSurfaceAssets,
    localize_buildings,
    rasterize_local_buildings,
)


def _rasterize_buildings(
    buildings: list[BuildingFeature],
    mapping: GridMapping,
    width: int,
    height: int,
    slice_height_agl_m: float | None,
    environment: EnvironmentData | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    if width <= 0 or height <= 0:
        raise ValueError("Coverage dimensions must be positive")
    east = mapping.first_sample_east_m + np.arange(width) * mapping.column_step_m
    north = mapping.first_sample_north_m + np.arange(height) * mapping.row_step_m
    localized = localize_buildings(
        buildings,
        mapping.origin_longitude,
        mapping.origin_latitude,
        environment,
    )
    return rasterize_local_buildings(localized, east, north, slice_height_agl_m, environment)


[docs] def rasterize_building_heights( buildings: list[BuildingFeature], mapping: GridMapping, width: int, height: int, receiver_height_agl_m: float, environment: EnvironmentData | None = None, ) -> tuple[np.ndarray, np.ndarray]: """Sample building occupancy at one AGL plane on exact grid cell centers.""" return _rasterize_buildings( buildings, mapping, width, height, receiver_height_agl_m, environment, )
[docs] def supersample_building_mask( buildings: list[BuildingFeature], mapping: GridMapping, width: int, height: int, receiver_height_agl_m: float, factor: int, environment: EnvironmentData | None = None, ) -> np.ndarray: """Sample building occupancy at one AGL plane on ``factor`` x ``factor`` points per cell. The points are the centres of an even split of each cell, so the mask has ``height * factor`` rows and ``width * factor`` columns in the mapping's row order. """ fine = mapping.model_copy( update={ "first_sample_east_m": mapping.first_sample_east_m + mapping.column_step_m * (1 / factor - 1) / 2, "first_sample_north_m": mapping.first_sample_north_m + mapping.row_step_m * (1 / factor - 1) / 2, "column_step_m": mapping.column_step_m / factor, "row_step_m": mapping.row_step_m / factor, } ) mask, _ = _rasterize_buildings( buildings, fine, width * factor, height * factor, receiver_height_agl_m, environment ) return mask
[docs] def rasterize_building_footprints( buildings: list[BuildingFeature], mapping: GridMapping, width: int, height: int, ) -> np.ndarray: """Sample the vertical building projection on exact grid cell centers.""" mask, _ = _rasterize_buildings(buildings, mapping, width, height, None) return mask
[docs] def surface_building_rasters( buildings: list[BuildingFeature], surface: MeasurementSurfaceAssets, origin_longitude: float, origin_latitude: float, receiver_height_agl_m: float, environment: EnvironmentData | None = None, ) -> dict[str, np.ndarray]: """Sample buildings at the cell centres of a measurement surface, rows south to north. ``footprint_mask`` marks cells whose centre lies in the vertical projection of a building, ``roof_height_agl_m`` holds the roof height above ground as the height map computes it (NaN where there is no building), and ``receiver_in_building_mask`` marks cells whose receiver point lies inside a building. With the scene's environment the samples follow the terrain, as the radio view's building mask does. """ east = np.asarray(surface.cell_centers[0, :, 0], dtype=np.float64) north = np.asarray(surface.cell_centers[:, 0, 1], dtype=np.float64) localized = localize_buildings(buildings, origin_longitude, origin_latitude, environment) footprint, roofs = rasterize_local_buildings(localized, east, north, None, environment) receiver, _ = rasterize_local_buildings( localized, east, north, receiver_height_agl_m, environment ) return { "footprint_mask": footprint.astype(BUILDING_MASK_DTYPE), "roof_height_agl_m": roofs.astype(BUILDING_ROOF_DTYPE), "receiver_in_building_mask": receiver.astype(BUILDING_MASK_DTYPE), }
def _write_building_rasters(path: Path, rasters: dict[str, np.ndarray]) -> Path: temporary = path.with_name(f"{path.name}.tmp") with temporary.open("wb") as handle: np.savez_compressed(handle, **rasters) temporary.replace(path) return path def _building_rasters_path(surface: MeasurementSurfaceAssets) -> Path: return surface.path.with_name(f"{surface.path.stem}{BUILDING_RASTERS_SUFFIX}")
[docs] def prepare_surface_building_rasters( buildings: list[BuildingFeature], surface: MeasurementSurfaceAssets, origin_longitude: float, origin_latitude: float, receiver_height_agl_m: float, environment: EnvironmentData | None = None, ) -> Path: """Keep the surface's building-raster file when it holds the current rasters, else write it. The rasters are always computed from the given buildings and terrain; the stored file is kept untouched only when it holds exactly these arrays, so re-fetched buildings or terrain replace it. """ path = _building_rasters_path(surface) rasters = surface_building_rasters( buildings, surface, origin_longitude, origin_latitude, receiver_height_agl_m, environment, ) try: with np.load(path) as archive: stored = {name: archive[name] for name in archive.files} except (OSError, ValueError, EOFError, zipfile.BadZipFile, zlib.error): stored = {} if set(stored) == set(rasters) and all( stored[name].dtype == array.dtype and np.array_equal(stored[name], array, equal_nan=array.dtype.kind == "f") for name, array in rasters.items() ): return path return _write_building_rasters(path, rasters)