Thibaut Forest Claude Opus 5 (1M context) commited on
Commit
2512a0a
·
1 Parent(s): 79a4af2

cv lobo: leave-one-building-out cost CV (user-specified primary) - per scenario x building, static fit on the other 23 buildings' full closed history, per-building plan+score; reports mean/bldg, sum, recall, and zero-swap-with-death count (the model-adaptation to-do list)

Browse files
Files changed (1) hide show
  1. batteryswap_example/cv.py +106 -0
batteryswap_example/cv.py CHANGED
@@ -758,6 +758,108 @@ def run_all48_oof(n_folds=5, seed=0, origins=range(48),
758
  return pd.DataFrame(recs)
759
 
760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
761
  # The re-test grid for the phase 52 addendum sweep: every prediction-side
762
  # candidate the campaign rejected on a self-fit or scenario-grouped surface,
763
  # re-asked on the building-OOF cost harness. Planner/appetite candidates are
@@ -888,6 +990,10 @@ def main():
888
  df['cand'] = label
889
  df.to_csv(f'/tmp/cv_oofcand_{label}.csv', index=False)
890
  scorecard(df, f'all48oof / cand={label} / oof arm / floor off')
 
 
 
 
891
  elif proto == 'oofreport':
892
  oof_candidate_report()
893
  elif proto == 'ablate':
 
758
  return pd.DataFrame(recs)
759
 
760
 
761
+ def run_lobo(origins=range(48), dataset_path=Path('dataset'), kind=None,
762
+ variant='base'):
763
+ """Leave-One-Building-Out CV (user-specified 2026-08-22): for each
764
+ scenario, for each building, train on ALL OTHER buildings' full closed
765
+ history (static, one fit per building - 24 fits total, reused across
766
+ scenarios) and plan/score THAT building alone in that scenario.
767
+
768
+ CV-first doctrine: this evaluates the current model as-is, including
769
+ where its count rule (N = 0.8 * sum p42) breaks at building scale -
770
+ those breaks are the model-adaptation to-do list, not instrument noise.
771
+ Per-building planning removes cross-building travel/limit coupling, so
772
+ this instrument governs prediction+inclusion (late/early, ~85% of cost);
773
+ routing questions keep the full-fleet harness as the secondary check.
774
+ """
775
+ kind = kind or CHAMPION['model']
776
+ t = load_table(dataset_path)
777
+ mc.FEATURES = list(VARIANTS[variant](t))
778
+ ctx = mc.load_context(dataset_path)
779
+ dev_bldg = (pd.read_csv(dataset_path / 'train' / 'devices.csv')
780
+ .drop_duplicates('device_id')
781
+ .set_index('device_id')['building_id'])
782
+ pool = t[t['origin'] <= t['origin'].max() - pd.Timedelta(days=WINDOW_DAYS)]
783
+ pool_b = pool['device_id'].map(dev_bldg)
784
+ make = ((lambda: mc.MODELS[kind]()) if kind in mc.MODELS
785
+ else (lambda: mc.SklearnRUL(kind)))
786
+ fits = {}
787
+ for b in sorted(dev_bldg.unique()):
788
+ fits[b] = make().fit(pool[(pool_b != b).values])
789
+ print(f'lobo: {len(fits)} leave-one-building-out static fits on '
790
+ f'{len(pool)} closed pairs', file=sys.stderr, flush=True)
791
+
792
+ p = mc.plan_tsroute
793
+ p.alpha, p.p_be, p.floor_day, p.p_conf = CHAMPION['p_star'], 0.0, 0, 0.5
794
+ p.ec_margin, p.ec_pmax = CHAMPION['ec_margin'], CHAMPION['ec_pmax']
795
+ p.split_days = CHAMPION['split_days']
796
+ p.floor_scale, p.recent_deaths = 0.0, 0.0
797
+
798
+ recs = []
799
+ for idx in origins:
800
+ c = ctx[idx]
801
+ T = c['start_time']
802
+ rows_all = (t[t['origin_idx'] == idx].set_index('device_id')
803
+ .reindex(c['locs']['battery']).dropna(subset=['v_last']))
804
+ for b, locs_b in c['locs'].groupby(c['locs']['battery'].map(dev_bldg)):
805
+ rows = rows_all.reindex(locs_b['battery']).dropna(subset=['v_last'])
806
+ if rows.empty:
807
+ continue
808
+ locs_b = locs_b[locs_b['battery'].isin(rows.index)]
809
+ eol_b = c['eol'].reindex(rows.index)
810
+ pred = fits[b].predict(rows)
811
+ plan = mc.plan_tsroute(pred, None, locs_b, T, CHAMPION['day_q'],
812
+ travel_costs=c['travel_costs'],
813
+ settings=c['settings'])
814
+ _, _, ov = evaluate_plan(plan, locs_b, c['travel_costs'],
815
+ c['settings'], eol_times=eol_b,
816
+ start_time=T, verbose=0)
817
+ WE = T + pd.Timedelta(days=WINDOW_DAYS)
818
+ deaths = set(eol_b.index[(eol_b > T) & (eol_b <= WE)])
819
+ sched = set(plan.loc[plan['day'] <= WE, 'battery'])
820
+ recs.append(dict(origin=idx, building=b, n_dev=len(rows),
821
+ total=ov['total_cost'], late=ov['late_swap'],
822
+ early=ov['early_swap'],
823
+ n_deaths=len(deaths), caught=len(sched & deaths),
824
+ n_sched=len(sched)))
825
+ d = pd.DataFrame([r for r in recs if r['origin'] == idx])
826
+ if not d.empty:
827
+ starved = int(((d['n_sched'] == 0) & (d['n_deaths'] > 0)).sum())
828
+ print(f"s_{idx}: mean/bldg {d['total'].mean():7.1f} "
829
+ f"sum {d['total'].sum():8.1f} "
830
+ f"deaths {int(d['n_deaths'].sum()):2d} caught "
831
+ f"{int(d['caught'].sum()):2d} zero-swap-with-death bldgs "
832
+ f"{starved}", flush=True, file=sys.stderr)
833
+ return pd.DataFrame(recs)
834
+
835
+
836
+ def lobo_report(df):
837
+ per = df.groupby('origin').agg(mean_bldg=('total', 'mean'),
838
+ sum_=('total', 'sum'),
839
+ deaths=('n_deaths', 'sum'),
840
+ caught=('caught', 'sum'),
841
+ sched=('n_sched', 'sum'))
842
+ print('\n=== lobo / leave-one-building-out, per scenario ===')
843
+ print(f"{'scen':>5s} {'mean/bldg':>9s} {'sum':>9s} {'deaths':>6s} "
844
+ f"{'caught':>6s} {'sched':>5s}")
845
+ for i, r in per.iterrows():
846
+ print(f"s_{i:<3d} {r['mean_bldg']:9.1f} {r['sum_']:9.1f} "
847
+ f"{int(r['deaths']):6d} {int(r['caught']):6d} {int(r['sched']):5d}")
848
+ for name, sel in BLOCKS:
849
+ m = per.index.to_series().apply(sel)
850
+ d = per[m.values]
851
+ if d.empty:
852
+ continue
853
+ dfb = df[df['origin'].isin(d.index)]
854
+ starved = int(((dfb['n_sched'] == 0) & (dfb['n_deaths'] > 0)).sum())
855
+ print(f"{name:16s} mean/bldg {d['mean_bldg'].mean():7.1f} "
856
+ f"sum/scen {d['sum_'].mean():8.1f} recall "
857
+ f"{d['caught'].sum() / max(d['deaths'].sum(), 1):.3f} "
858
+ f"zero-swap-death building-scenarios {starved}")
859
+ print('\nHEADLINE = mean/bldg on the panel. zero-swap-with-death = the '
860
+ 'count-granularity break the model adaptation must fix.')
861
+
862
+
863
  # The re-test grid for the phase 52 addendum sweep: every prediction-side
864
  # candidate the campaign rejected on a self-fit or scenario-grouped surface,
865
  # re-asked on the building-OOF cost harness. Planner/appetite candidates are
 
990
  df['cand'] = label
991
  df.to_csv(f'/tmp/cv_oofcand_{label}.csv', index=False)
992
  scorecard(df, f'all48oof / cand={label} / oof arm / floor off')
993
+ elif proto == 'lobo':
994
+ df = run_lobo()
995
+ df.to_csv('/tmp/cv_lobo.csv', index=False)
996
+ lobo_report(df)
997
  elif proto == 'oofreport':
998
  oof_candidate_report()
999
  elif proto == 'ablate':