566 lines
19 KiB
Python
566 lines
19 KiB
Python
import numpy as np
|
|
import asyncio
|
|
from typing import List, Optional, Tuple
|
|
from pydantic import BaseModel
|
|
from app.services.terrain_service import terrain_service, TerrainService
|
|
from app.services.los_service import los_service
|
|
from app.services.buildings_service import buildings_service, Building
|
|
from app.services.materials_service import materials_service
|
|
from app.services.dominant_path_service import dominant_path_service
|
|
from app.services.street_canyon_service import street_canyon_service, Street
|
|
from app.services.reflection_service import reflection_service
|
|
from app.services.spatial_index import get_spatial_index, SpatialIndex
|
|
from app.services.water_service import water_service, WaterBody
|
|
from app.services.vegetation_service import vegetation_service, VegetationArea
|
|
from app.services.weather_service import weather_service
|
|
from app.services.indoor_service import indoor_service
|
|
from app.services.atmospheric_service import atmospheric_service
|
|
|
|
|
|
class CoveragePoint(BaseModel):
|
|
lat: float
|
|
lon: float
|
|
rsrp: float # dBm
|
|
distance: float # meters from site
|
|
has_los: bool
|
|
terrain_loss: float # dB
|
|
building_loss: float # dB
|
|
reflection_gain: float = 0.0 # dB
|
|
vegetation_loss: float = 0.0 # dB
|
|
rain_loss: float = 0.0 # dB
|
|
indoor_loss: float = 0.0 # dB
|
|
atmospheric_loss: float = 0.0 # dB
|
|
|
|
|
|
class CoverageSettings(BaseModel):
|
|
radius: float = 10000 # meters
|
|
resolution: float = 200 # meters
|
|
min_signal: float = -120 # dBm threshold
|
|
|
|
# Layer toggles
|
|
use_terrain: bool = True
|
|
use_buildings: bool = True
|
|
use_materials: bool = True
|
|
use_dominant_path: bool = False
|
|
use_street_canyon: bool = False
|
|
use_reflections: bool = False
|
|
use_water_reflection: bool = False
|
|
use_vegetation: bool = False
|
|
|
|
# Vegetation season
|
|
season: str = "summer"
|
|
|
|
# Weather
|
|
rain_rate: float = 0.0 # mm/h (0=none, 5=light, 25=heavy)
|
|
|
|
# Indoor
|
|
indoor_loss_type: str = "none" # none, light, medium, heavy, vehicle
|
|
|
|
# Atmospheric
|
|
use_atmospheric: bool = False
|
|
temperature_c: float = 15.0
|
|
humidity_percent: float = 50.0
|
|
|
|
# Preset
|
|
preset: Optional[str] = None # fast, standard, detailed, full
|
|
|
|
|
|
# Propagation model presets
|
|
PRESETS = {
|
|
"fast": {
|
|
"use_terrain": True,
|
|
"use_buildings": False,
|
|
"use_materials": False,
|
|
"use_dominant_path": False,
|
|
"use_street_canyon": False,
|
|
"use_reflections": False,
|
|
"use_water_reflection": False,
|
|
"use_vegetation": False,
|
|
},
|
|
"standard": {
|
|
"use_terrain": True,
|
|
"use_buildings": True,
|
|
"use_materials": True,
|
|
"use_dominant_path": False,
|
|
"use_street_canyon": False,
|
|
"use_reflections": False,
|
|
"use_water_reflection": False,
|
|
"use_vegetation": False,
|
|
},
|
|
"detailed": {
|
|
"use_terrain": True,
|
|
"use_buildings": True,
|
|
"use_materials": True,
|
|
"use_dominant_path": True,
|
|
"use_street_canyon": False,
|
|
"use_reflections": False,
|
|
"use_water_reflection": False,
|
|
"use_vegetation": True,
|
|
},
|
|
"full": {
|
|
"use_terrain": True,
|
|
"use_buildings": True,
|
|
"use_materials": True,
|
|
"use_dominant_path": True,
|
|
"use_street_canyon": True,
|
|
"use_reflections": True,
|
|
"use_water_reflection": True,
|
|
"use_vegetation": True,
|
|
},
|
|
}
|
|
|
|
|
|
def apply_preset(settings: CoverageSettings) -> CoverageSettings:
|
|
"""Apply preset configuration to settings"""
|
|
if settings.preset and settings.preset in PRESETS:
|
|
for key, value in PRESETS[settings.preset].items():
|
|
setattr(settings, key, value)
|
|
return settings
|
|
|
|
|
|
class SiteParams(BaseModel):
|
|
lat: float
|
|
lon: float
|
|
height: float = 30 # antenna height meters
|
|
power: float = 43 # dBm (20W)
|
|
gain: float = 15 # dBi
|
|
frequency: float = 1800 # MHz
|
|
azimuth: Optional[float] = None # degrees, None = omni
|
|
beamwidth: Optional[float] = 65 # degrees
|
|
|
|
|
|
class CoverageService:
|
|
"""
|
|
RF Coverage calculation with terrain, buildings, materials,
|
|
dominant path, street canyon, reflections, water, and vegetation
|
|
"""
|
|
|
|
EARTH_RADIUS = 6371000
|
|
|
|
def __init__(self):
|
|
self.terrain = terrain_service
|
|
self.buildings = buildings_service
|
|
self.los = los_service
|
|
|
|
async def calculate_coverage(
|
|
self,
|
|
site: SiteParams,
|
|
settings: CoverageSettings
|
|
) -> List[CoveragePoint]:
|
|
"""
|
|
Calculate coverage grid for a single site
|
|
|
|
Returns list of CoveragePoint with RSRP values
|
|
"""
|
|
# Apply preset if specified
|
|
settings = apply_preset(settings)
|
|
|
|
points = []
|
|
|
|
# Generate grid
|
|
grid = self._generate_grid(
|
|
site.lat, site.lon,
|
|
settings.radius,
|
|
settings.resolution
|
|
)
|
|
|
|
# Calculate bbox for data fetching
|
|
lat_delta = settings.radius / 111000
|
|
lon_delta = settings.radius / (111000 * np.cos(np.radians(site.lat)))
|
|
|
|
min_lat = site.lat - lat_delta
|
|
max_lat = site.lat + lat_delta
|
|
min_lon = site.lon - lon_delta
|
|
max_lon = site.lon + lon_delta
|
|
|
|
# Fetch buildings (if enabled) and build spatial index
|
|
buildings: List[Building] = []
|
|
spatial_idx: Optional[SpatialIndex] = None
|
|
if settings.use_buildings:
|
|
buildings = await self.buildings.fetch_buildings(
|
|
min_lat, min_lon, max_lat, max_lon
|
|
)
|
|
if buildings:
|
|
cache_key = f"{min_lat:.3f},{min_lon:.3f},{max_lat:.3f},{max_lon:.3f}"
|
|
spatial_idx = get_spatial_index(cache_key, buildings)
|
|
|
|
# Fetch streets (if street canyon enabled)
|
|
streets: List[Street] = []
|
|
if settings.use_street_canyon:
|
|
streets = await street_canyon_service.fetch_streets(
|
|
min_lat, min_lon, max_lat, max_lon
|
|
)
|
|
|
|
# Fetch water bodies (if water reflection enabled)
|
|
water_bodies: List[WaterBody] = []
|
|
if settings.use_water_reflection:
|
|
water_bodies = await water_service.fetch_water_bodies(
|
|
min_lat, min_lon, max_lat, max_lon
|
|
)
|
|
|
|
# Fetch vegetation (if enabled)
|
|
vegetation_areas: List[VegetationArea] = []
|
|
if settings.use_vegetation:
|
|
vegetation_areas = await vegetation_service.fetch_vegetation(
|
|
min_lat, min_lon, max_lat, max_lon
|
|
)
|
|
|
|
# Calculate coverage for each point
|
|
for lat, lon in grid:
|
|
point = await self._calculate_point(
|
|
site, lat, lon,
|
|
settings, buildings, streets,
|
|
spatial_idx, water_bodies, vegetation_areas
|
|
)
|
|
|
|
if point.rsrp >= settings.min_signal:
|
|
points.append(point)
|
|
|
|
return points
|
|
|
|
async def calculate_multi_site_coverage(
|
|
self,
|
|
sites: List[SiteParams],
|
|
settings: CoverageSettings
|
|
) -> List[CoveragePoint]:
|
|
"""
|
|
Calculate combined coverage from multiple sites
|
|
Best server (strongest signal) wins at each point
|
|
"""
|
|
if not sites:
|
|
return []
|
|
|
|
# Apply preset once
|
|
settings = apply_preset(settings)
|
|
|
|
# Get all individual coverages
|
|
all_coverages = await asyncio.gather(*[
|
|
self.calculate_coverage(site, settings)
|
|
for site in sites
|
|
])
|
|
|
|
# Combine by best signal
|
|
point_map: dict[Tuple[float, float], CoveragePoint] = {}
|
|
|
|
for coverage in all_coverages:
|
|
for point in coverage:
|
|
key = (round(point.lat, 6), round(point.lon, 6))
|
|
|
|
if key not in point_map or point.rsrp > point_map[key].rsrp:
|
|
point_map[key] = point
|
|
|
|
return list(point_map.values())
|
|
|
|
def _generate_grid(
|
|
self,
|
|
center_lat: float, center_lon: float,
|
|
radius: float, resolution: float
|
|
) -> List[Tuple[float, float]]:
|
|
"""Generate coverage grid points"""
|
|
points = []
|
|
|
|
# Convert resolution to degrees
|
|
lat_step = resolution / 111000
|
|
lon_step = resolution / (111000 * np.cos(np.radians(center_lat)))
|
|
|
|
# Calculate grid bounds
|
|
lat_delta = radius / 111000
|
|
lon_delta = radius / (111000 * np.cos(np.radians(center_lat)))
|
|
|
|
lat = center_lat - lat_delta
|
|
while lat <= center_lat + lat_delta:
|
|
lon = center_lon - lon_delta
|
|
while lon <= center_lon + lon_delta:
|
|
# Check if within radius (circular, not square)
|
|
dist = TerrainService.haversine_distance(center_lat, center_lon, lat, lon)
|
|
if dist <= radius:
|
|
points.append((lat, lon))
|
|
lon += lon_step
|
|
lat += lat_step
|
|
|
|
return points
|
|
|
|
async def _calculate_point(
|
|
self,
|
|
site: SiteParams,
|
|
lat: float, lon: float,
|
|
settings: CoverageSettings,
|
|
buildings: List[Building],
|
|
streets: List[Street],
|
|
spatial_idx: Optional[SpatialIndex],
|
|
water_bodies: List[WaterBody],
|
|
vegetation_areas: List[VegetationArea]
|
|
) -> CoveragePoint:
|
|
"""Calculate RSRP at a single point with all propagation models"""
|
|
|
|
# Distance
|
|
distance = TerrainService.haversine_distance(site.lat, site.lon, lat, lon)
|
|
|
|
if distance < 1:
|
|
distance = 1 # Avoid division by zero
|
|
|
|
# Base path loss (Okumura-Hata for urban)
|
|
path_loss = self._okumura_hata(
|
|
distance, site.frequency, site.height, 1.5
|
|
)
|
|
|
|
# Antenna pattern loss (if directional)
|
|
antenna_loss = 0.0
|
|
if site.azimuth is not None and site.beamwidth:
|
|
antenna_loss = self._antenna_pattern_loss(
|
|
site.lat, site.lon, lat, lon,
|
|
site.azimuth, site.beamwidth
|
|
)
|
|
|
|
# Terrain loss (LoS check)
|
|
terrain_loss = 0.0
|
|
has_los = True
|
|
|
|
if settings.use_terrain:
|
|
los_result = await self.los.check_line_of_sight(
|
|
site.lat, site.lon, site.height,
|
|
lat, lon, 1.5
|
|
)
|
|
has_los = los_result["has_los"]
|
|
|
|
if not has_los:
|
|
clearance = los_result["clearance"]
|
|
terrain_loss = self._diffraction_loss(clearance, site.frequency)
|
|
|
|
# Building loss — use spatial index for fast lookup
|
|
building_loss = 0.0
|
|
nearby_buildings = (
|
|
spatial_idx.query_line(site.lat, site.lon, lat, lon)
|
|
if spatial_idx else buildings
|
|
)
|
|
|
|
if settings.use_buildings and nearby_buildings:
|
|
if settings.use_materials:
|
|
for building in nearby_buildings:
|
|
intersection = self.buildings.line_intersects_building(
|
|
site.lat, site.lon, site.height + await self.terrain.get_elevation(site.lat, site.lon),
|
|
lat, lon, 1.5 + await self.terrain.get_elevation(lat, lon),
|
|
building
|
|
)
|
|
if intersection is not None:
|
|
material = materials_service.detect_material(building.tags)
|
|
building_loss += materials_service.get_penetration_loss(
|
|
material, site.frequency
|
|
)
|
|
has_los = False
|
|
break
|
|
else:
|
|
for building in nearby_buildings:
|
|
intersection = self.buildings.line_intersects_building(
|
|
site.lat, site.lon, site.height + await self.terrain.get_elevation(site.lat, site.lon),
|
|
lat, lon, 1.5 + await self.terrain.get_elevation(lat, lon),
|
|
building
|
|
)
|
|
if intersection is not None:
|
|
building_loss += 20.0
|
|
has_los = False
|
|
break
|
|
|
|
# Dominant path analysis
|
|
if settings.use_dominant_path and nearby_buildings:
|
|
paths = await dominant_path_service.find_dominant_paths(
|
|
site.lat, site.lon, site.height,
|
|
lat, lon, 1.5,
|
|
site.frequency, nearby_buildings
|
|
)
|
|
if paths:
|
|
best_path = paths[0]
|
|
if best_path.is_valid and best_path.path_loss < (path_loss + terrain_loss + building_loss):
|
|
path_loss = best_path.path_loss
|
|
terrain_loss = 0
|
|
building_loss = 0
|
|
has_los = best_path.path_type == "direct" and not best_path.materials_crossed
|
|
|
|
# Street canyon model
|
|
if settings.use_street_canyon and streets:
|
|
canyon_loss, street_path = await street_canyon_service.calculate_street_canyon_loss(
|
|
site.lat, site.lon, site.height,
|
|
lat, lon, 1.5,
|
|
site.frequency, streets
|
|
)
|
|
if canyon_loss < (path_loss + terrain_loss + building_loss):
|
|
path_loss = canyon_loss
|
|
terrain_loss = 0
|
|
building_loss = 0
|
|
|
|
# Vegetation loss
|
|
veg_loss = 0.0
|
|
if settings.use_vegetation and vegetation_areas:
|
|
veg_loss = vegetation_service.calculate_vegetation_loss(
|
|
site.lat, site.lon, lat, lon,
|
|
vegetation_areas, settings.season
|
|
)
|
|
|
|
# Reflections (building + ground/water)
|
|
reflection_gain = 0.0
|
|
if settings.use_reflections and nearby_buildings:
|
|
is_over_water = False
|
|
if settings.use_water_reflection and water_bodies:
|
|
is_over_water = water_service.point_over_water(lat, lon, water_bodies) is not None
|
|
|
|
reflection_paths = await reflection_service.find_reflection_paths(
|
|
site.lat, site.lon, site.height,
|
|
lat, lon, 1.5,
|
|
site.frequency, nearby_buildings,
|
|
include_ground=True
|
|
)
|
|
|
|
# If over water, replace ground reflection with stronger water reflection
|
|
if is_over_water and reflection_paths:
|
|
water_path = reflection_service._calculate_ground_reflection(
|
|
site.lat, site.lon, site.height,
|
|
lat, lon, 1.5,
|
|
site.frequency, is_water=True
|
|
)
|
|
if water_path:
|
|
reflection_paths = [
|
|
p for p in reflection_paths if "ground" not in p.materials
|
|
]
|
|
reflection_paths.append(water_path)
|
|
reflection_paths.sort(key=lambda p: p.total_loss)
|
|
|
|
if reflection_paths:
|
|
direct_rsrp = site.power + site.gain - path_loss - antenna_loss - terrain_loss - building_loss - veg_loss
|
|
combined_rsrp = reflection_service.combine_paths(
|
|
direct_rsrp, reflection_paths, site.power + site.gain
|
|
)
|
|
reflection_gain = max(0, combined_rsrp - direct_rsrp)
|
|
elif settings.use_water_reflection and water_bodies and not settings.use_reflections:
|
|
# Water reflection without full reflection model
|
|
is_over_water = water_service.point_over_water(lat, lon, water_bodies) is not None
|
|
if is_over_water:
|
|
reflection_gain = 3.0 # ~3dB boost over water
|
|
|
|
# Rain attenuation
|
|
rain_loss = 0.0
|
|
if settings.rain_rate > 0:
|
|
rain_loss = weather_service.calculate_rain_attenuation(
|
|
site.frequency,
|
|
distance / 1000, # km
|
|
settings.rain_rate
|
|
)
|
|
|
|
# Indoor penetration loss
|
|
indoor_loss = 0.0
|
|
if settings.indoor_loss_type != "none":
|
|
indoor_loss = indoor_service.calculate_indoor_loss(
|
|
site.frequency,
|
|
settings.indoor_loss_type
|
|
)
|
|
|
|
# Atmospheric absorption
|
|
atmo_loss = 0.0
|
|
if settings.use_atmospheric:
|
|
atmo_loss = atmospheric_service.calculate_atmospheric_loss(
|
|
site.frequency,
|
|
distance / 1000,
|
|
settings.temperature_c,
|
|
settings.humidity_percent
|
|
)
|
|
|
|
# Final RSRP
|
|
rsrp = (site.power + site.gain - path_loss - antenna_loss
|
|
- terrain_loss - building_loss - veg_loss
|
|
- rain_loss - indoor_loss - atmo_loss
|
|
+ reflection_gain)
|
|
|
|
return CoveragePoint(
|
|
lat=lat,
|
|
lon=lon,
|
|
rsrp=rsrp,
|
|
distance=distance,
|
|
has_los=has_los,
|
|
terrain_loss=terrain_loss,
|
|
building_loss=building_loss,
|
|
reflection_gain=reflection_gain,
|
|
vegetation_loss=veg_loss,
|
|
rain_loss=rain_loss,
|
|
indoor_loss=indoor_loss,
|
|
atmospheric_loss=atmo_loss,
|
|
)
|
|
|
|
def _okumura_hata(
|
|
self,
|
|
distance: float,
|
|
frequency: float,
|
|
tx_height: float,
|
|
rx_height: float
|
|
) -> float:
|
|
"""Okumura-Hata path loss model (urban). Returns path loss in dB."""
|
|
d_km = distance / 1000
|
|
|
|
if d_km < 0.1:
|
|
d_km = 0.1
|
|
|
|
a_hm = (1.1 * np.log10(frequency) - 0.7) * rx_height - (1.56 * np.log10(frequency) - 0.8)
|
|
|
|
L = (69.55 + 26.16 * np.log10(frequency) - 13.82 * np.log10(tx_height) - a_hm +
|
|
(44.9 - 6.55 * np.log10(tx_height)) * np.log10(d_km))
|
|
|
|
return L
|
|
|
|
def _antenna_pattern_loss(
|
|
self,
|
|
site_lat: float, site_lon: float,
|
|
point_lat: float, point_lon: float,
|
|
azimuth: float, beamwidth: float
|
|
) -> float:
|
|
"""Calculate antenna pattern attenuation"""
|
|
bearing = self._calculate_bearing(site_lat, site_lon, point_lat, point_lon)
|
|
|
|
angle_diff = abs(bearing - azimuth)
|
|
if angle_diff > 180:
|
|
angle_diff = 360 - angle_diff
|
|
|
|
half_beamwidth = beamwidth / 2
|
|
|
|
if angle_diff <= half_beamwidth:
|
|
loss = 3 * (angle_diff / half_beamwidth) ** 2
|
|
else:
|
|
loss = 3 + 12 * ((angle_diff - half_beamwidth) / half_beamwidth) ** 2
|
|
loss = min(loss, 25)
|
|
|
|
return loss
|
|
|
|
def _calculate_bearing(
|
|
self,
|
|
lat1: float, lon1: float,
|
|
lat2: float, lon2: float
|
|
) -> float:
|
|
"""Calculate bearing from point 1 to point 2 (degrees)"""
|
|
lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])
|
|
|
|
dlon = lon2 - lon1
|
|
|
|
x = np.sin(dlon) * np.cos(lat2)
|
|
y = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(dlon)
|
|
|
|
bearing = np.degrees(np.arctan2(x, y))
|
|
|
|
return (bearing + 360) % 360
|
|
|
|
def _diffraction_loss(self, clearance: float, frequency: float) -> float:
|
|
"""Knife-edge diffraction loss. Returns additional loss in dB."""
|
|
if clearance >= 0:
|
|
return 0.0
|
|
|
|
v = abs(clearance) / 10
|
|
|
|
if v <= 0:
|
|
loss = 0
|
|
elif v < 2.4:
|
|
loss = 6.02 + 9.11 * v - 1.27 * v**2
|
|
else:
|
|
loss = 13.0 + 20 * np.log10(v)
|
|
|
|
return min(loss, 40)
|
|
|
|
|
|
# Singleton
|
|
coverage_service = CoverageService()
|