atmosiq-processed / scripts /build_group_d.py
AtmosIQ's picture
Upload scripts/build_group_d.py with huggingface_hub
0257519 verified
Raw History Blame Contribute Delete
6.26 kB
r"""
build_group_d.py -> Group D calendar/event features (Data_Schema: COMPUTED from date, not stored).
Encodes the AtmosIQ event reference (festivals, stubble-burning, monsoon, COVID, GRAP, holidays,
heatwave) into a per-DATE feature matrix + grap_stage categorical. Node-independent (broadcast).
Output (called by assemble.py): calendar_num [D, K], grap_stage [D].
Columns (K): doy_sin doy_cos month_sin month_cos dow_sin dow_cos is_weekend is_holiday
festival_firecracker festival_biomass crop_burning_intensity
days_since_monsoon_onset days_to_monsoon_withdrawal is_monsoon_active
covid_lockdown_intensity heatwave_season
grap_stage: 0..4 categorical (documented anchors; AQI-driven toggling approximated).
NOTE: node-specific events (Kumbh at Prayagraj) are NOT Group D (date-only). Handle separately if needed.
"""
from __future__ import annotations
import numpy as np, pandas as pd
# ---- event dates (from AtmosIQ Group-D reference doc) ----
DIWALI = {2018:"11-07",2019:"10-27",2020:"11-14",2021:"11-04",2022:"10-24",2023:"11-12",2024:"10-31",2025:"10-20",2026:"11-08"}
DUSSEHRA = {2018:"10-19",2019:"10-08",2020:"10-25",2021:"10-15",2022:"10-05",2023:"10-24",2024:"10-12",2025:"10-02",2026:"10-20"}
HOLI = {2018:"03-02",2019:"03-21",2020:"03-10",2021:"03-29",2022:"03-18",2023:"03-08",2024:"03-25",2025:"03-14",2026:"03-04"}
MONSOON_ONSET = {2018:"05-29",2019:"06-08",2020:"06-01",2021:"06-03",2022:"05-29",2023:"06-08",2024:"05-30",2025:"05-24",2026:"06-04"}
MONSOON_WITHDRAW = {y:f"{y}-10-15" for y in range(2018,2027)} # withdrawal complete ~mid-Oct (doc)
# COVID lockdown intensity (national approximation): date-range -> intensity 0..1
COVID = [("2020-03-25","2020-04-14",1.0),("2020-04-15","2020-05-03",0.9),("2020-05-04","2020-05-17",0.7),
("2020-05-18","2020-05-31",0.5),("2020-06-01","2020-10-31",0.25),("2021-04-19","2021-06-07",0.6)]
# GRAP documented anchor blocks (stage active windows); pre-2021 coarse. (year-specific)
GRAP = [("2022-10-05","2022-10-18",1),("2022-10-19","2022-10-28",2),("2022-10-29","2022-11-14",3),("2022-12-04","2022-12-31",3),
("2023-10-06","2023-11-01",1),("2023-11-02","2023-12-21",3),("2023-12-22","2024-01-01",3),
("2024-10-22","2024-11-14",2),("2024-11-15","2024-11-17",3),("2024-11-18","2024-12-16",4),
("2025-10-14","2025-12-12",1),("2025-12-13","2026-01-31",3),
("2018-11-01","2019-01-31",1),("2019-11-01","2020-01-31",1),("2020-11-01","2021-01-31",1),("2021-10-15","2022-01-31",1)]
def _bump(dts, anchor_mmdd_by_year, sigma=2.0, pre=1, post=1):
"""gaussian proximity to a per-year event date (captures ±window)."""
out=np.zeros(len(dts))
for i,d in enumerate(dts):
y=d.year; mmdd=anchor_mmdd_by_year.get(y)
if not mmdd: continue
ev=pd.Timestamp(f"{y}-{mmdd}"); delta=(d-ev).days
if -pre-3<=delta<=post+3: out[i]=np.exp(-(delta**2)/(2*sigma**2))
return out
def build(dates):
dts=pd.to_datetime(dates); n=len(dts)
doy=dts.dayofyear.values; mo=dts.month.values; dow=dts.dayofweek.values
two=lambda x,p:(np.sin(2*np.pi*x/p),np.cos(2*np.pi*x/p))
s1,c1=two(doy,365.25); s2,c2=two(mo,12); s3,c3=two(dow,7)
is_weekend=(dow>=5).astype(float)
# holidays: fixed national + major festival days (low industrial activity)
fixed={(1,26),(8,15),(10,2),(12,25)}
is_holiday=np.array([1.0 if (d.month,d.day) in fixed else 0.0 for d in dts])
firecracker=np.maximum.reduce([_bump(dts,DIWALI,2.0,1,2), _bump(dts,DUSSEHRA,1.5,0,1)]) # firecracker/effigy
biomass=_bump(dts,HOLI,1.5,1,0) + np.array([1.0 if (d.month,d.day)==(1,13) else 0.0 for d in dts]) # Holi + Lohri
biomass=np.clip(biomass,0,1)
# crop burning: smooth ramp 25 Sep -> 30 Nov, peak 25 Oct-15 Nov
def cb(d):
doyv=d.dayofyear; start,pk0,pk1,end=268,298,319,334 # ~Sep25,Oct25,Nov15,Nov30
if doyv<start or doyv>end: return 0.0
if doyv<pk0: return (doyv-start)/(pk0-start)
if doyv<=pk1: return 1.0
return max(0.0,(end-doyv)/(end-pk1))
crop=np.array([cb(d) for d in dts])
# monsoon phase
dso=np.zeros(n); dtw=np.zeros(n); active=np.zeros(n)
for i,d in enumerate(dts):
y=d.year; on=pd.Timestamp(f"{y}-{MONSOON_ONSET[y]}"); wd=pd.Timestamp(MONSOON_WITHDRAW[y])
dso[i]=np.clip((d-on).days/120.0,-1,2); dtw[i]=np.clip((wd-d).days/120.0,-1,2)
active[i]=1.0 if on<=d<=wd else 0.0
# covid
covid=np.zeros(n)
for a,b,v in COVID:
m=(dts>=pd.Timestamp(a))&(dts<=pd.Timestamp(b)); covid[m]=np.maximum(covid[m],v)
# heatwave season (Apr-Jun ramp, O3 relevant)
heat=np.array([max(0.0,1-abs(d.dayofyear-135)/60.0) for d in dts]) # peak ~mid-May
# grap_stage categorical
grap=np.zeros(n,dtype=np.int64)
for a,b,st in GRAP:
m=(dts>=pd.Timestamp(a))&(dts<=pd.Timestamp(b)); grap[m]=np.maximum(grap[m],st)
cal=np.column_stack([s1,c1,s2,c2,s3,c3,is_weekend,is_holiday,firecracker,biomass,
crop,dso,dtw,active,covid,heat]).astype(np.float32) # K=16
return cal, grap
COLS=["doy_sin","doy_cos","month_sin","month_cos","dow_sin","dow_cos","is_weekend","is_holiday",
"festival_firecracker","festival_biomass","crop_burning_intensity",
"days_since_monsoon_onset","days_to_monsoon_withdrawal","is_monsoon_active",
"covid_lockdown_intensity","heatwave_season"]
if __name__=="__main__":
d=pd.date_range("2018-01-01","2026-07-18").strftime("%Y-%m-%d").tolist()
cal,grap=build(d)
print(f"Group D: {cal.shape} num cols + grap_stage (0..{grap.max()})")
import pandas as pd
df=pd.DataFrame(cal,columns=COLS); df["date"]=d; df["grap"]=grap
for c in ["festival_firecracker","crop_burning_intensity","covid_lockdown_intensity"]:
print(f" {c}: nonzero days = {(df[c]>0).sum()}, max {df[c].max():.2f}")
print(" grap_stage counts:", pd.Series(grap).value_counts().sort_index().to_dict())
print(" Diwali 2021-11-04 firecracker:", round(float(df[df.date=='2021-11-04'].festival_firecracker.iloc[0]),2))
print(" crop peak 2021-11-01:", round(float(df[df.date=='2021-11-01'].crop_burning_intensity.iloc[0]),2))