File size: 7,470 Bytes
124816b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""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<self.rain_duration_min:raise ValueError('Hourly series must cover the entire rainfall duration')
        return self

def simulate(cfg:Scenario):
    a,t,crs=load_grid(cfg.terrain_id); z=a['z']; valid=a['valid']; n,m=z.shape
    dx,dy=abs(t.a),abs(t.e); cell=dx*dy
    depth=np.zeros_like(z); initial_label='NONE'
    if cfg.geometry_id:
        g=get('geometries',cfg.geometry_id)
        gs=[transform_geom('EPSG:4326',crs,f['geometry']) for f in g['geojson']['features']]
        depth[rasterize([(g,1) for g in gs],out_shape=z.shape,transform=t).astype(bool)&valid]=cfg.initial_depth_m
        initial_label='MANUALLY EDITED INPUT'
    infra=get('assets',cfg.infrastructure_id) if cfg.infrastructure_id else None
    features=(infra or {}).get('geojson',{}).get('features',[])
    projector=Transformer.from_crs(4326,crs,always_xy=True).transform
    infra_shapes=[shape_transform(projector,shape(f['geometry'])) for f in features]
    inlet=int(np.argmin(np.where(valid[0],z[0],np.inf)))
    if not valid[0].any() and cfg.upstream_m3_s: raise ValueError('No valid upstream boundary cells')
    volume0=float(depth.sum()*cell); inputs=0.; infiltrated=0.; outflow=0.; first={}; frames=[]
    all_depth=[]; elapsed=0.
    targets=list(np.arange(0,cfg.duration_min*60, cfg.output_step_min*60))+[cfg.duration_min*60]
    # Adaptive substep bound for diffusive exchange; donor limiting keeps nonnegative volume.
    stable=min(10.,.2*min(dx,dy)/cfg.conductivity_m_s)
    for target in targets:
        while elapsed<target-1e-8:
            dt=min(stable,target-elapsed,3600-(elapsed%3600))
            rain_dt=max(0.,min(elapsed+dt,cfg.rain_duration_min*60)-elapsed)
            rain_rate=cfg.rainfall_series_mm_h[min(int(elapsed//3600),len(cfg.rainfall_series_mm_h)-1)] if cfg.rainfall_series_mm_h else cfg.rainfall_mm_h
            add=rain_rate/3.6e6*rain_dt*cfg.runoff
            depth[valid]+=add; inputs+=add*int(valid.sum())*cell
            if cfg.upstream_m3_s:
                depth[0,inlet]+=cfg.upstream_m3_s*dt/cell; inputs+=cfg.upstream_m3_s*dt
            loss=np.minimum(depth,cfg.infiltration_mm_h/3.6e6*dt)*valid
            depth-=loss; infiltrated+=float(loss.sum()*cell)
            head=z+depth
            # Four-neighbor edge exchange driven by water-surface head. Dry barriers cannot emit.
            qx=cfg.conductivity_m_s*(head[:,:-1]-head[:,1:])/dx*dt
            qy=cfg.conductivity_m_s*(head[:-1,:]-head[1:,:])/dy*dt
            qx*=valid[:,:-1]&valid[:,1:]; qy*=valid[:-1,:]&valid[1:,:]
            outgoing=np.zeros_like(depth)
            outgoing[:,:-1]+=np.maximum(qx,0); outgoing[:,1:]+=np.maximum(-qx,0)
            outgoing[:-1,:]+=np.maximum(qy,0); outgoing[1:,:]+=np.maximum(-qy,0)
            factor=np.minimum(1.,depth/np.maximum(outgoing,1e-12))
            qx*=np.where(qx>=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<cfg.rain_duration_min*60 else 0,
            'warning_tier':'EXPERIMENTAL ELEVATED' if any(x['exposed'] for x in exposed) else 'NO MODELED INTERSECTION'})
        all_depth.append(depth.astype('float32'))
    result=put('simulations',{'config':cfg.model_dump(),'created_at':now(),'frames':frames,'initial_input':initial_label,
        'terrain_source':get('assets',cfg.terrain_id),'infrastructure_source':infra,
        'provenance':'SIMULATED SCENARIO','model_version':'head-routing-1.0',
        'mass_balance':{'initial_m3':volume0,'input_m3':inputs,'infiltration_m3':infiltrated,'outflow_m3':outflow,'final_m3':frames[-1]['volume_m3'],
            'residual_m3':volume0+inputs-infiltrated-outflow-frames[-1]['volume_m3']},
        'warnings':['Research routing model, not validated flood prediction','Uniform assumed rainfall; no catchment calibration','South boundary open, other boundaries closed','Depth is model state, not measured inundation']})
    np.savez_compressed(path_for(result['id'],'depth.npz'),depth=np.stack(all_depth))
    return result