"""Reproduce the frozen, audited submission from local inputs, without network access.""" import argparse import hashlib import json import os from pathlib import Path import sys # Apply before importing any forecasting dependency. The download scripts are separate. def disable_network(event, args): if event.startswith('socket.'): raise PermissionError('The forecast process is offline; only the audited local inputs may be used.') sys.addaudithook(disable_network) os.environ['OPENBLAS_NUM_THREADS']='1' os.environ['OMP_NUM_THREADS']='1' import numpy as np import pandas as pd from inputs import Panel, ROOT, DATA, LAST, METRICS from models import Origin from experiments import generate as core from advanced import generate as adv from climate import generate as climate from teleconnection import run as tele from selection import combine, membership from direct import origin_features, predict as direct_predict def verify_files(): records=json.loads((DATA/'input_audit.json').read_text()) for row in records: p=DATA/row['file'] if p.name=='daily.parquet' and not p.exists(): continue # Source is optional once its audited monthly aggregates are included. with p.open('rb') as f: digest=hashlib.file_digest(f,'sha256').hexdigest() if digest!=row['sha256']: raise ValueError(f'Unexpected bytes in {p.name}; restore the audited snapshot.') print('Verified audited input fingerprints; forecast is offline.') def run_models(p,weights): if 'global_weights' in weights: portfolios=[weights['global_weights'],*weights['regional_weights']] else: portfolios=[weights] required={name for w in portfolios for metric in w.values() for name in metric} groups={ 'core':{'normal','line','fast','transform','season','persist','forced','ocean'}, 'adv':{'curve','gain','station','gamma'}, 'climate':{'pattern','extreme'},'tele':{'tele'},'direct':{'direct'}, } active={name.split(':',1)[0] for name in required} o=Origin(p,LAST,7); out={} if groups['direct']&active: years=np.arange(1935,2019); vals,sc,x=zip(*(origin_features(p,y) for y in years)) a=np.full_like(vals,np.nan,dtype='float64') for i,y in enumerate(years): h=min(LAST-y,7) if h:a[i,:h]=p.actual(y,h) cube=years,np.stack(vals),np.stack(sc),np.stack(x),a k={b:o.spatial(b) for b in [550,1050]} for name in sorted(required): if name.startswith('direct:'): _,w,b,g,r,inter=name.split(':') out[name]=direct_predict(cube,LAST,7,k,int(w),float(r),int(b),g,float(inter),.65).astype('float32') for label,gen in [('core',core),('adv',adv),('climate',climate),('tele',tele)]: if not groups[label]&active: continue for n,pred in gen(o): if n in required:out[n]=pred.astype('float32') if required<=out.keys(): break if required!=out.keys():raise ValueError(f'Missing trained variants: {required-out.keys()}') names=sorted(out); preds=np.stack([out[n] for n in names]); return combine(names,preds,weights,membership(p)) def write_submission(p,values,path): if values.shape!=(7,len(p.ids),len(METRICS)) or not np.isfinite(values).all(): raise ValueError('Invalid forecast shape or non-finite value') ix=pd.MultiIndex.from_product([range(LAST+1,LAST+8),p.ids,METRICS],names=['year','city_id','metric']) pred=pd.Series(values.ravel(),index=ix,name='predicted_value') blank=pd.read_csv(DATA/'submission_template.csv') if blank.shape!=(5880,4) or list(blank)!=['city_id','year','metric','predicted_value'] or blank.predicted_value.notna().any(): raise ValueError('Expected official blank submission template') wanted=pd.MultiIndex.from_frame(blank[['year','city_id','metric']]); blank['predicted_value']=pred.reindex(wanted).to_numpy() if wanted.has_duplicates or not np.isfinite(blank.predicted_value).all(): raise ValueError('Invalid city-year-metric keys') blank.to_csv(path,index=False,float_format='%.6f',lineterminator='\n') print(f'Wrote {len(blank):,} forecasts to {path}') def main(): ap=argparse.ArgumentParser(description=__doc__); ap.add_argument('--output',type=Path,default=ROOT/'submission.csv'); args=ap.parse_args() verify_files(); p=Panel(); model=json.loads((ROOT/'code/ensemble.json').read_text()); pred=run_models(p,model['weights']) write_submission(p,pred,args.output) if __name__=='__main__':main()