sanvicpatel's picture
Upload reproducible Protostar climate forecasts
993d9a6 verified
Raw History Blame Contribute Delete
7.31 kB
"""Load only declared, date-audited inputs and construct the city-year panel."""
from pathlib import Path
import calendar
import hashlib
import json
import numpy as np
import pandas as pd
import pyarrow.parquet as pq
ROOT=Path(__file__).resolve().parents[1]
DATA=ROOT/'data'
CUTOFF=pd.Timestamp('2018-12-31')
LAST=2018
METRICS=('annual_avg_temp','total_precip_in','hottest_day_temp','cdd')
COLS=('Avg Temp','ToT Prcp','Max Tmax','cdd')
MONTH_LENGTH=np.array([31,28.25,31,30,31,30,31,31,30,31,30,31])
def dates(series, name):
date=pd.to_datetime(series,errors='raise')
if date.isna().any() or (date>CUTOFF).any():
raise ValueError(f'{name}: missing or post-cutoff weather date')
return date
def years(series,name):
y=pd.to_numeric(series,errors='raise')
if y.isna().any() or (y>LAST).any() or (y<1700).any() or (y%1!=0).any():
raise ValueError(f'{name}: invalid or post-cutoff weather year')
return y.astype(int)
def parquet(name, cols, date_cols=(), year_col=None):
p=DATA/f'{name}.parquet'
a=pd.read_parquet(p,columns=cols)
for c in date_cols: a[c]=dates(a[c],name)
if year_col: a[year_col]=years(a[year_col],name)
return a
def prepare_daily():
# Validate every row before any year filter. Only numeric aggregates are written.
d=parquet('daily',['ID','Date','tmax','tmin','prcp'],date_cols=['Date'])
d['Year']=d.Date.dt.year; d['Month']=d.Date.dt.month
d['T']=(d.tmax+d.tmin)*.5
d['CDD']=(d['T']-65).clip(lower=0)
d['WARM']=np.where(d['T'].notna(),d['T']>65,np.nan)
d['P2']=d.prcp**2
d['WET']=np.where(d.prcp.notna(),d.prcp>0,np.nan)
monthly=d.groupby(['ID','Year','Month'],sort=True).agg(
T=('T','mean'),TX=('tmax','mean'),TN=('tmin','mean'),N=('T','count'),
CDD=('CDD','mean'),WARM=('WARM','mean'),P=('prcp','mean'),PN=('prcp','count'),
WET=('WET','mean'),P2=('P2','mean'),MAX=('tmax','max'),XN=('tmax','count')).reset_index()
q90=d.groupby(['ID','Year','Month'],sort=True).tmax.quantile(.9).rename('Q90').reset_index()
monthly=monthly.merge(q90,on=['ID','Year','Month'],validate='one_to_one')
monthly.to_parquet(DATA/'monthly.parquet',index=False)
return dict(file='daily.parquet',rows=len(d),first_date=str(d.Date.min().date()),last_date=str(d.Date.max().date()))
class Panel:
def __init__(self, monthly=True, sst=True):
a=parquet('annual_indices',['ID','Name','Lat','Lon','Year','Miss Tmax','Miss Tmin','Miss Prcp',*COLS,'Avg Tmax','Avg Tmin'],year_col='Year')
c=parquet('coverage_and_stations',['ID','Year','Days Both','Station Segment','Station Changes'],year_col='Year')
info=parquet('city_info',['ID','Stn.stDate','Stn.edDate'],date_cols=['Stn.stDate','Stn.edDate'])
self.audit=[dict(file=f'{name}.parquet',rows=len(frame),first_year=int(frame.Year.min()),last_year=int(frame.Year.max())) for name,frame in [('annual_indices',a),('coverage_and_stations',c)]]
self.audit.append(dict(file='city_info.parquet',rows=len(info),first_date=str(info['Stn.stDate'].min().date()),last_date=str(info['Stn.edDate'].max().date())))
if a[['ID','Year']].duplicated().any() or c[['ID','Year']].duplicated().any(): raise ValueError('Duplicate station-years')
a=a.merge(c,on=['ID','Year'],how='left',validate='one_to_one')
if a['Station Segment'].isna().any(): raise ValueError('Missing coverage metadata')
self.ids=sorted(info.ID.unique())
if len(self.ids)!=210 or set(a.ID)!=set(self.ids): raise ValueError('Expected all 210 cities')
self.yrs=np.arange(a.Year.min(),LAST+1)
self.idx=pd.MultiIndex.from_product([self.yrs,self.ids],names=['Year','ID'])
self.cities=a.drop_duplicates('ID').set_index('ID').reindex(self.ids)
self.lat=self.cities.Lat.to_numpy(); self.lon=self.cities.Lon.to_numpy()
a=a.set_index(['Year','ID']).reindex(self.idx)
self.raw=self.arr(a[list(COLS)])
tgood=((a['Miss Tmax']<=10)&(a['Miss Tmin']<=10)).to_numpy().reshape(-1,len(self.ids))
pgood=(a['Miss Prcp']<=10).to_numpy().reshape(-1,len(self.ids))
self.valid=np.stack([tgood,pgood,tgood,tgood],axis=-1)&np.isfinite(self.raw)
self.y=np.where(self.valid,self.raw,np.nan)
self.segment=self.arr(a[['Station Segment']])[:,:,0]
self.changes=self.arr(a[['Station Changes']])[:,:,0]
self.tminmax=self.arr(a[['Avg Tmax','Avg Tmin']])
self.month=None
if monthly:
m=parquet('monthly',['ID','Year','Month','T','TX','TN','N','CDD','WARM','P','PN','WET','P2','MAX','XN','Q90'],year_col='Year')
if not m.Month.isin(range(1,13)).all(): raise ValueError('Invalid month')
self.audit.append(dict(file='monthly.parquet',rows=len(m),first_year=int(m.Year.min()),last_year=int(m.Year.max())))
im=pd.MultiIndex.from_product([self.yrs,self.ids,range(1,13)],names=['Year','ID','Month'])
m=m.set_index(['Year','ID','Month']).reindex(im)
self.month={col:m[col].to_numpy().reshape(-1,len(self.ids),12) for col in m}
for col in ['T','TX','TN','CDD','WARM','MAX','Q90']:
self.month[col]=np.where(self.month['N']>=MONTH_LENGTH-5,self.month[col],np.nan)
for col in ['P','WET','P2']:
self.month[col]=np.where(self.month['PN']>=MONTH_LENGTH-5,self.month[col],np.nan)
self.sst=None
if sst and (DATA/'ersst_v5_regions.csv').is_file():
o=pd.read_csv(DATA/'ersst_v5_regions.csv'); o.date=dates(o.date,'ERSSTv5')
if o.date.duplicated().any() or o.drop(columns='date').isna().any().any(): raise ValueError('Invalid ERSST records')
self.audit.append(dict(file='ersst_v5_regions.csv',rows=len(o),first_date=str(o.date.min().date()),last_date=str(o.date.max().date())))
self.sst=o.set_index('date')
self.global_temp=None
if (DATA/'noaa_global_annual.csv').is_file():
g=pd.read_csv(DATA/'noaa_global_annual.csv'); g.year=years(g.year,'NOAA CAG')
if g.year.duplicated().any() or not np.isfinite(g.to_numpy()).all(): raise ValueError('Invalid global temperature series')
self.audit.append(dict(file='noaa_global_annual.csv',rows=len(g),first_year=int(g.year.min()),last_year=int(g.year.max())))
self.global_temp=g.set_index('year')
def arr(self,df):
return df.to_numpy(dtype='float64').reshape(len(self.yrs),len(self.ids),-1)
def baseline(self,origin,horizon):
x=self.y[(self.yrs>origin-30)&(self.yrs<=origin)]
count=np.isfinite(x).sum(axis=0)
mean=np.nansum(x,axis=0)/np.maximum(count,1)
return np.tile(np.where(count>=10,mean,np.nan),(horizon,1,1))
def actual(self,origin,horizon):
if origin+horizon>LAST: raise ValueError('Scoring after the cutoff is forbidden')
return self.y[(self.yrs>origin)&(self.yrs<=origin+horizon)]
if __name__=='__main__':
import sys
daily=prepare_daily() if '--prepare-daily' in sys.argv else None
p=Panel()
records=p.audit+([daily] if daily else [])
for f in records: f['sha256']=hashlib.sha256((DATA/f['file']).read_bytes()).hexdigest()
(ROOT/'reports/input_audit.json').write_text(json.dumps(records,indent=2)+'\n')
print(json.dumps(records,indent=2))