"""Conservative head-gradient routing prototype, not a shallow-water solver.""" import numpy as np from pydantic import BaseModel, Field, model_validator, ConfigDict from typing import Optional from rasterio.features import rasterize from rasterio.warp import transform_geom from shapely.geometry import shape from shapely.ops import transform as shape_transform from pyproj import Transformer from .geo import load_grid, polygons from .store import get, put, now, path_for class Scenario(BaseModel): model_config=ConfigDict(allow_inf_nan=False) terrain_id:str name:str=Field(default='Rainfall scenario',max_length=100) rainfall_mm_h:float=Field(default=35,ge=0,le=300) rainfall_series_mm_h:Optional[list[float]]=Field(default=None,min_length=1,max_length=6) rain_duration_min:float=Field(default=45,gt=0,le=360) infiltration_mm_h:float=Field(default=8,ge=0,le=200) runoff:float=Field(default=.65,ge=0,le=1) upstream_m3_s:float=Field(default=4,ge=0,le=500) duration_min:float=Field(default=90,gt=0,le=360) output_step_min:float=Field(default=5,ge=1,le=30) initial_depth_m:float=Field(default=.1,ge=0,le=5) geometry_id:Optional[str]=None infrastructure_id:Optional[str]=None depth_threshold_m:float=Field(default=.03,ge=.005,le=1) conductivity_m_s:float=Field(default=2.,gt=0,le=20) @model_validator(mode='after') def frames_limit(self): if self.duration_min/self.output_step_min>120: raise ValueError('At most 120 output steps') if self.rainfall_series_mm_h is not None: if any(not np.isfinite(x) or not 0<=x<=300 for x in self.rainfall_series_mm_h):raise ValueError('Hourly rainfall must be finite and between 0 and 300 mm/h') if len(self.rainfall_series_mm_h)*60=0,factor[:,:-1],factor[:,1:]); qy*=np.where(qy>=0,factor[:-1,:],factor[1:,:]) depth[:,:-1]-=qx; depth[:,1:]+=qx; depth[:-1,:]-=qy; depth[1:,:]+=qy # South open boundary with finite drainage speed; other boundaries closed. drained=np.minimum(depth[-1],depth[-1]*cfg.conductivity_m_s*dt/dy) depth[-1]-=drained; outflow+=float(drained.sum()*cell) depth=np.maximum(depth,0); elapsed+=dt mask=(depth>=cfg.depth_threshold_m)&valid fc=polygons(mask,t,crs,{'kind':'SIMULATED SCENARIO','time_min':target/60}) from shapely.ops import unary_union flooded=unary_union([shape_transform(projector,shape(f['geometry'])) for f in fc['features']]) exposed=[]; by_category={} for k,(f,s) in enumerate(zip(features,infra_shapes)): hit=s.intersects(flooded) if not flooded.is_empty else False fid=str(f.get('id',k)); category=f.get('properties',{}).get('category','custom') if hit: first.setdefault(fid,target/60); by_category[category]=by_category.get(category,0)+1 exposed.append({'id':fid,'name':f.get('properties',{}).get('name',f'{category} {fid}'),'category':category,'exposed':hit, 'distance_m':None if flooded.is_empty else round(s.distance(flooded),2),'first_exposure_min':first.get(fid)}) frames.append({'time_min':target/60,'area_km2':float(mask.sum()*cell/1e6),'max_depth_m':float(depth.max()), 'volume_m3':float(depth.sum()*cell),'exposed_count':sum(x['exposed'] for x in exposed),'by_category':by_category, 'exposure':exposed,'extent':fc,'rainfall_mm_h':(cfg.rainfall_series_mm_h[min(int(target//3600),len(cfg.rainfall_series_mm_h)-1)] if cfg.rainfall_series_mm_h else cfg.rainfall_mm_h) if target