saef-api / backend /drought.py
m4az19's picture
Deploy SAHAB-1 backend and pretrained AI
124816b verified
Raw History Blame Contribute Delete
4.92 kB
"""Seasonal SPI-3 from ERA5 reanalysis; no custom ML training or inferred gauges.
1991–2020 is the fixed reference. Complete calendar months only. Arid-season
zero inflation and inadequate records suppress classification rather than turning
normal UAE desert conditions into invented drought severity.
"""
import calendar
import math
from datetime import date, timedelta
import httpx
import numpy as np
from scipy.stats import gamma, norm
from . import store
from .locations import require_uae
VERSION='era5-spi3-1'
def last_month(today=None):
today=today or date.today()
return today.replace(day=1)-timedelta(days=1)
def window(end):
index=end.year*12+end.month-1-2
return date(index//12,index%12+1,1),end
def severity(value):
return ('extremely dry' if value<=-2 else 'severely dry' if value<=-1.5 else
'moderately dry' if value<=-1 else 'near normal' if value<1 else
'moderately wet' if value<1.5 else 'very wet' if value<2 else 'extremely wet')
def calculate(daily,end):
times=daily.get('time',[]);rain=daily.get('precipitation_sum',[])
if len(times)!=len(rain) or len(set(times))!=len(times):raise ValueError('Rainfall dates are missing or duplicated')
series={date.fromisoformat(day):value for day,value in zip(times,rain)}
def total(ending):
start,finish=window(ending);values=[];day=start
while day<=finish:
value=series.get(day)
if value is None or not isinstance(value,(int,float)) or not math.isfinite(value) or value<0:return None
values.append(value);day+=timedelta(days=1)
return float(sum(values))
observed=total(end)
baseline=[total(date(year,end.month,calendar.monthrange(year,end.month)[1])) for year in range(1991,2021)]
complete=[v for v in baseline if v is not None]
result={'status':'insufficient_data','spi3':None,'classification':'unavailable',
'period_start':window(end)[0].isoformat(),'period_end':end.isoformat(),
'precipitation_mm':observed,'reference_years':'1991–2020','reference_samples':len(complete),
'reference_mean_mm':float(np.mean(complete)) if complete else None,
'method':'SPI-3: calendar-season gamma MLE with zero-probability correction; normal inverse CDF',
'limitations':['ERA5 grid reanalysis, not local rain-gauge observations',
'Meteorological precipitation deficit only; no soil-moisture, crop-loss or groundwater diagnosis',
'Historical three-month indicator, not a six-hour drought forecast',
'Gamma-fit reliability in arid climates needs local independent validation']}
if observed is None or len(complete)<30:
return {**result,'reason':'Three complete current months and 30 complete reference seasons are required'}
positive=np.asarray([v for v in complete if v>0],float);q=1-len(positive)/len(complete)
if len(positive)<20 or q>=.5 or np.std(positive)<1e-6:
return {**result,'reason':'Too little rainfall variability or too many zero-rain seasons for reliable SPI fitting'}
shape,_,scale=gamma.fit(positive,floc=0)
probability=q+(1-q)*gamma.cdf(observed,shape,loc=0,scale=scale)
value=float(norm.ppf(np.clip(probability,1e-6,1-1e-6)))
return {**result,'status':'available','spi3':value,'classification':severity(value),
'reason':'Compared with the same three calendar months in each reference year',
'zero_rain_fraction':q,'gamma_shape':float(shape),'gamma_scale':float(scale)}
def acquire(wadi,lon,lat,today=None):
require_uae(lon,lat);end=last_month(today)
# ERA5 final/reanalysis availability lags; keep the month complete and explicit.
if ((today or date.today())-end).days<7:
end=last_month(end)
identity=f'{VERSION}:{wadi}:{end.isoformat()}'
try:return store.get('drought',identity)
except KeyError:pass
response=httpx.get('https://archive-api.open-meteo.com/v1/archive',params={
'latitude':lat,'longitude':lon,'start_date':'1990-01-01','end_date':end.isoformat(),
'daily':'precipitation_sum','models':'era5','timezone':'UTC'},timeout=90)
response.raise_for_status();data=response.json()
if data.get('daily_units',{}).get('precipitation_sum')!='mm':raise ValueError('Unexpected rainfall units')
result=calculate(data.get('daily',{}),end)
return store.put('drought',{**result,'wadi':wadi,'mode':'real','version':VERSION,
'created_at':store.now(),'source':'ERA5 via Open-Meteo historical weather',
'grid':{'latitude':data.get('latitude'),'longitude':data.get('longitude'),'spatial_support':'ERA5 reanalysis grid'},
'source_url':'https://open-meteo.com/en/docs/historical-weather-api'},identity)
def latest(wadi,mode):
if mode!='real':return None
records=[r for r in store.all_records('drought') if r['wadi']==wadi]
return max(records,key=lambda r:r['period_end'],default=None)