"""Test a player-informed center for the existing 200-possession same-five estimate. Fixed before fitting: 2022-23 to 2025-26, annual Jan 1 cutoff, only regular season, non-garbage stints with five distinct players each side. Fit one opponent-adjusted ridge (alpha=2000, weighted by estimated possessions) before each cutoff. Preserve the team's exposure-weighted average. Score later, actual lineup-team-games against the identical team-centered rule and a same-team shuffled identity control. This conditional task does not predict future minutes. """ import argparse import json from pathlib import Path import numpy as np import pandas as pd from scipy.sparse import csr_matrix from sklearn.linear_model import Ridge def ordered(values): return tuple(sorted(int(v) for v in values)) def sides(stints): parts = [] for side, opposite in (("home","away"),("away","home")): p = stints[["date","game_id",side,side+"_team_id","poss"]].copy() p = p.rename(columns={side:"five",side+"_team_id":"team"}) p["net"] = stints[side+"_pts"]-stints[opposite+"_pts"] parts.append(p) return pd.concat(parts, ignore_index=True) def trial(table, season): stints=table.loc[table.season_start_year.eq(season)].copy() cutoff=f"{season+1}-01-01" fit=stints.loc[stints.date.lt(cutoff)] train=sides(fit) later=sides(stints.loc[stints.date.ge(cutoff)]) test=later.groupby(["date","game_id","team","five"],as_index=False)[["net","poss"]].sum() ids=sorted(set().union(*(fit.home.tolist()+fit.away.tolist()))) index={player:idx for idx,player in enumerate(ids)} columns=[[index[p] for p in home+away] for home,away in zip(fit.home,fit.away)] if not columns:raise ValueError("Missing training stints") x=csr_matrix((np.tile([1]*5+[-1]*5,len(fit)), (np.arange(len(fit)).repeat(10),np.array(columns).ravel())),shape=(len(fit),len(ids))) model=Ridge(alpha=2000,solver="lsqr").fit(x,(fit.home_pts-fit.away_pts)/fit.poss,sample_weight=fit.poss) coefficients=dict(zip(ids,model.coef_)) known=train.groupby(["team","five"],as_index=False)[["net","poss"]].sum() by_team=train.groupby("team")[["net","poss"]].sum() rng=np.random.default_rng(4100+season) shuffles={} for team,frame in known.groupby("team"): players=sorted(set().union(*frame.five)) shuffles[team]=dict(zip(players,rng.permutation([coefficients[p] for p in players]))) def raw_prior(frame, placebo=False): return np.array([sum((shuffles.get(team,{}) if placebo else coefficients).get(p,0) for p in five) for team,five in zip(frame.team,frame.five)]) means={} for key in ("player","shuffle"): raw=raw_prior(known, key=="shuffle") means[key]=(known.assign(weighted=raw*known.poss).groupby("team").weighted.sum()/by_team.poss) known=known.rename(columns={"net":"past_net","poss":"past_poss"}) test=test.merge(known,on=["team","five"],how="left",validate="many_to_one") test["seen"]=test.past_poss.notna() test[["past_net","past_poss"]]=test[["past_net","past_poss"]].fillna(0) base=test.team.map(by_team.net / by_team.poss) if base.isna().any():raise ValueError("Held-out team absent from training") for key in ("team","player","shuffle"): prior=base if key=="team" else base+raw_prior(test,key=="shuffle")-test.team.map(means[key]) estimate=(test.past_net+200*prior)/(test.past_poss+200) test[key+"_error"]=(estimate*test.poss-test.net).abs() test["season"]=season test["week"]=pd.to_datetime(test.date).dt.to_period("W").astype(str) return test def summary(frame): metrics=["team_error","player_error","shuffle_error"] blocks=frame.groupby("week")[["poss"]+metrics].sum() rng=np.random.default_rng(2811) idx=rng.integers(0,len(blocks),size=(4000,len(blocks))) delta=(blocks.player_error-blocks.team_error).to_numpy() interval=np.quantile(100*delta[idx].sum(axis=1)/blocks.poss.to_numpy()[idx].sum(axis=1),[.025,.975]) return {"games":int(frame.game_id.nunique()),"lineup_team_games":len(frame),"weeks":len(blocks), "possessions_both_team_perspectives":float(frame.poss.sum()), "mae_per_100":{k.replace("_error",""):round(100*frame[k].sum()/frame.poss.sum(),4) for k in metrics}, "weekly_95_player_minus_team":[round(float(x),4) for x in interval]} def main(): ap=argparse.ArgumentParser(description=__doc__) ap.add_argument("parquet",type=Path) ap.add_argument("result",type=Path) args=ap.parse_args() cols=["date","game_id","home","away","home_team_id","away_team_id","home_pts","away_pts","home_poss","away_poss","season_start_year"] table=pd.read_parquet(args.parquet,columns=cols,filters=[("season_start_year",">=",2022),("season_start_year","<=",2025), ("season_type","=","Regular Season"),("garbage","=",False)]) table["date"]=pd.to_datetime(table.date).dt.strftime("%Y-%m-%d") table["poss"]=(table.home_poss+table.away_poss)/2 table=table.loc[table.poss.gt(0)].copy() for side in ("home","away"): table[side]=table[side].map(ordered) table=table.loc[table[side].map(lambda v:len(v)==len(set(v))==5)] table=table.loc[[not set(h).intersection(a) for h,a in zip(table.home,table.away)]] scores=pd.concat([trial(table,y) for y in range(2022,2026)],ignore_index=True) out={"task":"Later stint performance conditional on the actual five players who appeared","all":summary(scores), "seen":summary(scores.loc[scores.seen]),"unseen":summary(scores.loc[~scores.seen]), "seasons":{str(y):summary(f) for y,f in scores.groupby("season")}} args.result.write_text(json.dumps(out,indent=2)+"\n") print(out["all"]) if __name__=="__main__": main()