Thibaut Forest Claude Opus 5 (1M context) commited on
Commit ·
30e8503
1
Parent(s): b636dfd
Phase 7: full coordinate sweep finds nothing - champion is a local optimum
Browse files~25 knob values across forecast (C, bags, day-model GBR, recency weighting,
training-set variants incl. discrete hazard and determined labels, blends)
and optimization (emergency-day anchor, search budget, tspig/tspig2
routing-aware inclusion). Acceptance rule (>=60 dev AND >=10/16 origins)
adopted nothing; best was bags=30 at -9.4. dthaz statistically tied using a
different likelihood. Champion unchanged: logbag/tsroute/a0.8, dev 2073.9,
test 1398, public 1767.87 (rank 2). EXPERIMENTS.md updated with phases 5-7,
public LB readings, and full champion spec. Also wires SklearnRUL variant
specs (bags/dtrees/ddepth/q6) and per-config search knobs into the harness.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- EXPERIMENTS.md +52 -11
- batteryswap_example/models_cv.py +450 -14
EXPERIMENTS.md
CHANGED
|
@@ -84,6 +84,13 @@ ranks, physics projections.
|
|
| 84 |
| aggressive challenger α=1.15 | — | 1516 (look 7) | leader-like profile (late 722/early 550); kept as `BATTERYSWAP_ALPHA` knob, not default |
|
| 85 |
| **adaptive runtime refit** (`submit.py`) | | | refits at every scenario origin on the target split's own self-masked history; honest all-48 train metric 2202; 280 s/split native; deadline guards → static-pickle fallback |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
## Phase 6 - voltage-silent deaths (exploration, all rejected by CV)
|
| 88 |
|
| 89 |
Silent deaths are **fast plungers**, not a separate mechanism: all 16 deaths that
|
|
@@ -97,23 +104,57 @@ before - the same 2.40 V crossing, compressed into ~3 weeks.
|
|
| 97 |
| install-cohort clock (age - batch median lifetime) | **AUC 0.906** on silent pairs; batch explains ~90% of lifetime variance | 2074 -> 2279 (raw), 2433 (overdue-neutral encoding) | **rejected**: 14%/54% coverage - the no-information majority degrades the fit in every encoding |
|
| 98 |
| alpha re-sweep 0.7-1.3 (public-LB-motivated 1.15) | public late/early ratio 8 vs leaders' ~1 | minimum stays at **0.8** (2074; 1.15: 2219, losing 12/16 origins) | 1.15 reverted; late saturates ~1100 for alpha >= 1.15 - remaining misses are not an inclusion problem |
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
## Trajectory
|
| 101 |
|
| 102 |
-
| champion | dev | test | combined (34) | all-48 metric |
|
| 103 |
-
|---|---|---|---|---|
|
| 104 |
-
| shipped example | — | 6779 | — | 8673 |
|
| 105 |
-
| defer-everything | — | 2512 | — | 3325 |
|
| 106 |
-
| voltage-15 | — | 2034 | — | — |
|
| 107 |
-
| logistic + fixed p0.5 | 2473 | 1735 | 2082 | — |
|
| 108 |
-
| **v1** topsum
|
| 109 |
-
| + features + ecroute | 2197 | 1478 | 1816 | — |
|
| 110 |
-
| + synthetic origins (tsroute) | 2126 | 1476 | 1782 | — |
|
| 111 |
-
| + tau_projected | 2147 | 1439 | 1772 | 2081 |
|
| 112 |
-
| **current**: + bagging + search + adaptive runtime | 2074 | 1398 | **1716** | 2202* |
|
| 113 |
|
| 114 |
\* honest walk-forward (adaptive path), not comparable to earlier in-sample-ish
|
| 115 |
pickle numbers.
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
Oracle bound: 186 (test). Remaining gap is dominated by deaths with p42 < 0.10 -
|
| 118 |
batteries whose voltage has not moved by the origin (27 of 60 test misses).
|
| 119 |
|
|
|
|
| 84 |
| aggressive challenger α=1.15 | — | 1516 (look 7) | leader-like profile (late 722/early 550); kept as `BATTERYSWAP_ALPHA` knob, not default |
|
| 85 |
| **adaptive runtime refit** (`submit.py`) | | | refits at every scenario origin on the target split's own self-masked history; honest all-48 train metric 2202; 280 s/split native; deadline guards → static-pickle fallback |
|
| 86 |
|
| 87 |
+
**Public leaderboard (2026-08-18, adaptive submission): 1767.87, rank 2** - v1 was
|
| 88 |
+
1964.29. Mobility+limits 315.9 now beats the leader astar's 334.6; the whole
|
| 89 |
+
remaining gap to astar (1652.6) is timing balance (our late/early 1296/156 vs
|
| 90 |
+
their 660/658). An α=1.15 change motivated by that profile was committed, then
|
| 91 |
+
reverted before submission: the local α sweep rejected it (see phase 6) -
|
| 92 |
+
selection stays on CV, not public feedback.
|
| 93 |
+
|
| 94 |
## Phase 6 - voltage-silent deaths (exploration, all rejected by CV)
|
| 95 |
|
| 96 |
Silent deaths are **fast plungers**, not a separate mechanism: all 16 deaths that
|
|
|
|
| 104 |
| install-cohort clock (age - batch median lifetime) | **AUC 0.906** on silent pairs; batch explains ~90% of lifetime variance | 2074 -> 2279 (raw), 2433 (overdue-neutral encoding) | **rejected**: 14%/54% coverage - the no-information majority degrades the fit in every encoding |
|
| 105 |
| alpha re-sweep 0.7-1.3 (public-LB-motivated 1.15) | public late/early ratio 8 vs leaders' ~1 | minimum stays at **0.8** (2074; 1.15: 2219, losing 12/16 origins) | 1.15 reverted; late saturates ~1100 for alpha >= 1.15 - remaining misses are not an inclusion problem |
|
| 106 |
|
| 107 |
+
## Phase 7 - full coordinate sweep (nothing adopted; champion is a local optimum)
|
| 108 |
+
|
| 109 |
+
One-knob-at-a-time sweep around the champion, ~25 knob values across both axes.
|
| 110 |
+
Acceptance rule fixed in advance: adopt only if dev improves by >= 60 AND wins
|
| 111 |
+
>= 10/16 origins head-to-head. Full cartesian grids were ruled out: dev's
|
| 112 |
+
resolution is ~150 points (16 correlated origins), so a large grid guarantees
|
| 113 |
+
spurious winners.
|
| 114 |
+
|
| 115 |
+
| axis | best variant | Δ vs champion 2073.9 | verdict |
|
| 116 |
+
|---|---|---|---|
|
| 117 |
+
| bag count | 30 bags | −9.4 | closest of all; 6x short of the bar |
|
| 118 |
+
| search budget | restarts 4 / iters 120 | −0.4 | saturated |
|
| 119 |
+
| day-model GBR | dtrees=50 | −0.6 | insensitive |
|
| 120 |
+
| regularization | C=0.3 | +64.8 | C=1.0 confirmed (0.1: +148.6, 3.0: +76.7) |
|
| 121 |
+
| training set | dthaz (discrete-time hazard, open windows) | +15.4 | statistically tied while using a different likelihood and more data - the natural committee partner if one is ever wanted |
|
| 122 |
+
| recency weighting | half-life 240d | +30.7 | no drift-adaptation gain (120d: +99.7) |
|
| 123 |
+
| blends | logbag+gbm | +190.6 | GBM drags; blend_dh +1367.9 |
|
| 124 |
+
| routing-aware inclusion | tspig membership repair | +46.5 | right shape, does not pay at these travel costs |
|
| 125 |
+
| piggyback inclusion | tspig2 α₂=1.3 / 1.6 | +293.1 / +497.7 | over-includes |
|
| 126 |
+
| determined labels | logbag_open | +3080 (std 11k) | blows up at early origins - tiny determined sets |
|
| 127 |
+
|
| 128 |
+
Disclosures: `emergency_day` is structurally inert for tsroute (it prices parking,
|
| 129 |
+
which the count rule never consults); the q6 day-quantile grid is inert because
|
| 130 |
+
cost_curves reads only the four standard quantile columns (CDF-resolution axis
|
| 131 |
+
untested); `logbag_aux*` variants await their feature columns in the table.
|
| 132 |
+
|
| 133 |
+
**Conclusion**: every axis is flat or worse around the champion - remaining cost
|
| 134 |
+
is structural (fast-plunge deaths), not hyperparameters.
|
| 135 |
+
|
| 136 |
## Trajectory
|
| 137 |
|
| 138 |
+
| champion | dev | test | combined (34) | all-48 metric | public LB |
|
| 139 |
+
|---|---|---|---|---|---|
|
| 140 |
+
| shipped example | — | 6779 | — | 8673 | — |
|
| 141 |
+
| defer-everything | — | 2512 | — | 3325 | — |
|
| 142 |
+
| voltage-15 | — | 2034 | — | — | — |
|
| 143 |
+
| logistic + fixed p0.5 | 2473 | 1735 | 2082 | — | — |
|
| 144 |
+
| **v1** topsum | 2502 | 1368 | 1901 | 2150 | 1964.29 (rank 3) |
|
| 145 |
+
| + features + ecroute | 2197 | 1478 | 1816 | — | — |
|
| 146 |
+
| + synthetic origins (tsroute) | 2126 | 1476 | 1782 | — | — |
|
| 147 |
+
| + tau_projected | 2147 | 1439 | 1772 | 2081 | — |
|
| 148 |
+
| **current**: + bagging + search + adaptive runtime | **2074** | **1398** | **1716** | 2202* | **1767.87 (rank 2)** |
|
| 149 |
|
| 150 |
\* honest walk-forward (adaptive path), not comparable to earlier in-sample-ish
|
| 151 |
pickle numbers.
|
| 152 |
|
| 153 |
+
Current champion in full: **logbag (15-bag logistic, C=1.0, 13 features) +
|
| 154 |
+
tsroute (topsum inclusion α=0.8, expected-cost day placement, merge-move day
|
| 155 |
+
search against the exact mobility simulator) + adaptive per-origin runtime
|
| 156 |
+
refits**, confirmed a local optimum by the phase-7 sweep.
|
| 157 |
+
|
| 158 |
Oracle bound: 186 (test). Remaining gap is dominated by deaths with p42 < 0.10 -
|
| 159 |
batteries whose voltage has not moved by the origin (27 of 60 test misses).
|
| 160 |
|
batteryswap_example/models_cv.py
CHANGED
|
@@ -68,18 +68,22 @@ DAY_QUANTILES = (0.05, 0.20, 0.50, 0.80)
|
|
| 68 |
class DayQuantiles:
|
| 69 |
"""Quantiles of days-to-EOL, fit on training pairs that died in-window."""
|
| 70 |
|
| 71 |
-
def __init__(self):
|
| 72 |
self.models = {}
|
| 73 |
self.fallback = {}
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
def fit(self, X, days):
|
| 76 |
-
for q in
|
| 77 |
self.fallback[q] = float(np.quantile(days, q))
|
| 78 |
if len(days) >= 40:
|
| 79 |
m = make_pipeline(
|
| 80 |
SimpleImputer(strategy='median'),
|
| 81 |
GradientBoostingRegressor(loss='quantile', alpha=q,
|
| 82 |
-
n_estimators=
|
|
|
|
| 83 |
random_state=0))
|
| 84 |
m.fit(X, days)
|
| 85 |
self.models[q] = m
|
|
@@ -87,7 +91,7 @@ class DayQuantiles:
|
|
| 87 |
|
| 88 |
def predict(self, X):
|
| 89 |
out = {}
|
| 90 |
-
for q in
|
| 91 |
if q in self.models:
|
| 92 |
out[f'day_q{q}'] = np.clip(self.models[q].predict(X), 0, WINDOW_DAYS)
|
| 93 |
else:
|
|
@@ -95,10 +99,18 @@ class DayQuantiles:
|
|
| 95 |
return pd.DataFrame(out, index=X.index)
|
| 96 |
|
| 97 |
|
|
|
|
|
|
|
|
|
|
| 98 |
class SklearnRUL:
|
| 99 |
"""p42 from a sklearn classifier + DayQuantiles for timing."""
|
| 100 |
|
| 101 |
def __init__(self, kind):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
self.kind = kind
|
| 103 |
|
| 104 |
def fit(self, train):
|
|
@@ -125,12 +137,18 @@ class SklearnRUL:
|
|
| 125 |
from sklearn.ensemble import BaggingClassifier
|
| 126 |
base = make_pipeline(SimpleImputer(strategy='median'),
|
| 127 |
StandardScaler(),
|
| 128 |
-
LogisticRegression(max_iter=2000,
|
| 129 |
-
|
|
|
|
|
|
|
| 130 |
self.clf.fit(X, y)
|
| 131 |
|
| 132 |
dying = train[train['dies42'] == 1]
|
| 133 |
-
self.days = DayQuantiles(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
return self
|
| 135 |
|
| 136 |
def predict(self, rows):
|
|
@@ -196,6 +214,230 @@ class WeibullAFT:
|
|
| 196 |
return out
|
| 197 |
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
MODELS = {
|
| 200 |
'rank-v': RankVoltage,
|
| 201 |
'logistic': lambda: SklearnRUL('logistic'),
|
|
@@ -203,9 +445,27 @@ MODELS = {
|
|
| 203 |
'logbag': lambda: SklearnRUL('logbag'),
|
| 204 |
'gbm': lambda: SklearnRUL('gbm'),
|
| 205 |
'aft': WeibullAFT,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
}
|
| 207 |
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
# ------------------------------------------------------------------------- planners
|
| 210 |
|
| 211 |
def assemble(selected_days, locations, start_time):
|
|
@@ -448,7 +708,9 @@ def mobility_cost(day_batteries, locations, travel_hours, settings, start_time):
|
|
| 448 |
|
| 449 |
|
| 450 |
def optimize_days(groups, curves, locations, travel_hours, settings, start_time,
|
| 451 |
-
restarts=
|
|
|
|
|
|
|
| 452 |
"""
|
| 453 |
Local search over building-group visit days: shift moves, merge moves (jump a
|
| 454 |
group onto another group's day), and deterministic random restarts.
|
|
@@ -496,6 +758,10 @@ def optimize_days(groups, curves, locations, travel_hours, settings, start_time,
|
|
| 496 |
return best
|
| 497 |
|
| 498 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
def plan_ecroute(pred, included, locations, start_time, day_q,
|
| 500 |
travel_costs=None, settings=None, margin=None):
|
| 501 |
"""
|
|
@@ -575,9 +841,162 @@ plan_tsroute.p_be = 0.0
|
|
| 575 |
plan_tsroute.floor_day = 0
|
| 576 |
plan_tsroute.p_conf = 0.5
|
| 577 |
|
| 578 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
'expcost': plan_expcost, 'topsum': plan_topsum,
|
| 580 |
-
'ecday': plan_ecday, 'ecroute': plan_ecroute, 'tsroute': plan_tsroute
|
|
|
|
| 581 |
|
| 582 |
|
| 583 |
# ------------------------------------------------------------------------ harness
|
|
@@ -609,8 +1028,8 @@ def walk_forward(table, scenario_ctx, origins, configs):
|
|
| 609 |
preds = {}
|
| 610 |
for model_name in {c['model'] for c in configs}:
|
| 611 |
if (model_name, idx) not in fitted:
|
| 612 |
-
factory =
|
| 613 |
-
if model_name
|
| 614 |
train = censored_pairs(table, origin_time)
|
| 615 |
else:
|
| 616 |
train = training_pairs(table, origin_time)
|
|
@@ -624,14 +1043,23 @@ def walk_forward(table, scenario_ctx, origins, configs):
|
|
| 624 |
if cfg['planner'] == 'ecroute':
|
| 625 |
PLANNERS['ecroute'].margin = cfg['p_star'] or 1.0 # p_star carries margin
|
| 626 |
PLANNERS['ecroute'].blend = cfg.get('blend', 0.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
if cfg['planner'] == 'tsroute':
|
| 628 |
PLANNERS['tsroute'].alpha = cfg['p_star'] or 0.8 # p_star carries alpha
|
| 629 |
PLANNERS['tsroute'].p_be = cfg.get('p_be', 0.0)
|
| 630 |
PLANNERS['tsroute'].floor_day = cfg.get('floor_day', 0)
|
| 631 |
PLANNERS['tsroute'].p_conf = cfg.get('p_conf', 0.5)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
included = pred.index[pred['p42'] >= cfg['p_star']]
|
| 633 |
kwargs = {}
|
| 634 |
-
if cfg['planner'] in ('ecroute', 'tsroute'):
|
| 635 |
kwargs = dict(travel_costs=ctx['travel_costs'],
|
| 636 |
settings=ctx['settings'])
|
| 637 |
plan = PLANNERS[cfg['planner']](pred, included, ctx['locs'],
|
|
@@ -663,7 +1091,9 @@ def load_context(dataset_path):
|
|
| 663 |
def summarize(df, label):
|
| 664 |
df['name'] = (df['model'] + '/' + df['planner'] + '/p' +
|
| 665 |
df['p_star'].astype(str) + '/q' + df['day_q'].astype(str))
|
| 666 |
-
for key, tag in [('blend', 'b'), ('p_be', 'be'), ('floor_day', 'f'), ('p_conf', 'c')
|
|
|
|
|
|
|
| 667 |
if key in df.columns and df[key].nunique(dropna=False) > 1:
|
| 668 |
df['name'] += '/' + tag + df[key].fillna(0).astype(str)
|
| 669 |
mean = df.groupby('name')['total_cost'].agg(['mean', 'std']).sort_values('mean')
|
|
@@ -675,6 +1105,12 @@ def summarize(df, label):
|
|
| 675 |
def main():
|
| 676 |
dataset_path = Path(os.environ.get('BATTERYSWAP_DATASET_PATH', 'dataset'))
|
| 677 |
table = load_features(dataset_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
ctx = load_context(dataset_path)
|
| 679 |
|
| 680 |
phase = sys.argv[1] if len(sys.argv) > 1 else 'dev'
|
|
|
|
| 68 |
class DayQuantiles:
|
| 69 |
"""Quantiles of days-to-EOL, fit on training pairs that died in-window."""
|
| 70 |
|
| 71 |
+
def __init__(self, n_estimators=100, max_depth=2, quantiles=DAY_QUANTILES):
|
| 72 |
self.models = {}
|
| 73 |
self.fallback = {}
|
| 74 |
+
self.n_estimators = n_estimators
|
| 75 |
+
self.max_depth = max_depth
|
| 76 |
+
self.quantiles = quantiles
|
| 77 |
|
| 78 |
def fit(self, X, days):
|
| 79 |
+
for q in self.quantiles:
|
| 80 |
self.fallback[q] = float(np.quantile(days, q))
|
| 81 |
if len(days) >= 40:
|
| 82 |
m = make_pipeline(
|
| 83 |
SimpleImputer(strategy='median'),
|
| 84 |
GradientBoostingRegressor(loss='quantile', alpha=q,
|
| 85 |
+
n_estimators=self.n_estimators,
|
| 86 |
+
max_depth=self.max_depth,
|
| 87 |
random_state=0))
|
| 88 |
m.fit(X, days)
|
| 89 |
self.models[q] = m
|
|
|
|
| 91 |
|
| 92 |
def predict(self, X):
|
| 93 |
out = {}
|
| 94 |
+
for q in self.quantiles:
|
| 95 |
if q in self.models:
|
| 96 |
out[f'day_q{q}'] = np.clip(self.models[q].predict(X), 0, WINDOW_DAYS)
|
| 97 |
else:
|
|
|
|
| 99 |
return pd.DataFrame(out, index=X.index)
|
| 100 |
|
| 101 |
|
| 102 |
+
Q6 = (0.05, 0.10, 0.20, 0.35, 0.50, 0.80)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
class SklearnRUL:
|
| 106 |
"""p42 from a sklearn classifier + DayQuantiles for timing."""
|
| 107 |
|
| 108 |
def __init__(self, kind):
|
| 109 |
+
self.opts = {}
|
| 110 |
+
if ':' in kind:
|
| 111 |
+
kind, spec = kind.split(':', 1)
|
| 112 |
+
self.opts = {k: float(v) for k, v in
|
| 113 |
+
(kv.split('=') for kv in spec.split(','))}
|
| 114 |
self.kind = kind
|
| 115 |
|
| 116 |
def fit(self, train):
|
|
|
|
| 137 |
from sklearn.ensemble import BaggingClassifier
|
| 138 |
base = make_pipeline(SimpleImputer(strategy='median'),
|
| 139 |
StandardScaler(),
|
| 140 |
+
LogisticRegression(max_iter=2000,
|
| 141 |
+
C=self.opts.get('C', 1.0)))
|
| 142 |
+
self.clf = BaggingClassifier(
|
| 143 |
+
base, n_estimators=int(self.opts.get('bags', 15)), random_state=0)
|
| 144 |
self.clf.fit(X, y)
|
| 145 |
|
| 146 |
dying = train[train['dies42'] == 1]
|
| 147 |
+
self.days = DayQuantiles(
|
| 148 |
+
n_estimators=int(self.opts.get('dtrees', 100)),
|
| 149 |
+
max_depth=int(self.opts.get('ddepth', 2)),
|
| 150 |
+
quantiles=Q6 if self.opts.get('q6') else DAY_QUANTILES,
|
| 151 |
+
).fit(dying[FEATURES], dying['days_to_eol'])
|
| 152 |
return self
|
| 153 |
|
| 154 |
def predict(self, rows):
|
|
|
|
| 214 |
return out
|
| 215 |
|
| 216 |
|
| 217 |
+
class DiscreteHazard:
|
| 218 |
+
"""
|
| 219 |
+
Discrete-time hazard logistic on person-period (pair, week-bucket) rows.
|
| 220 |
+
|
| 221 |
+
Trains on ALL prior pairs, not just closed windows: a pair whose window is
|
| 222 |
+
still open at the scored origin contributes its observed buckets (event if
|
| 223 |
+
the death is already visible, censored otherwise). Recovers the freshest
|
| 224 |
+
training data - the six origins immediately before the scored one - which
|
| 225 |
+
training_pairs() discards entirely.
|
| 226 |
+
|
| 227 |
+
p42 = 1 - prod_k (1 - h_k); conditional day quantiles from the bucket CDF.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
BUCKET = 7.0
|
| 231 |
+
K = 6 # buckets cover days (7k, 7(k+1)], k=0..5
|
| 232 |
+
|
| 233 |
+
def fit(self, train_censored):
|
| 234 |
+
dur = train_censored['duration'].clip(upper=WINDOW_DAYS).values
|
| 235 |
+
event = ((train_censored['event'] == 1) &
|
| 236 |
+
(train_censored['duration'] <= WINDOW_DAYS)).values
|
| 237 |
+
X = train_censored[FEATURES].values
|
| 238 |
+
rows, ys, ks = [], [], []
|
| 239 |
+
for k in range(self.K):
|
| 240 |
+
lo, hi = self.BUCKET * k, self.BUCKET * (k + 1)
|
| 241 |
+
died_here = event & (dur > lo) & (dur <= hi)
|
| 242 |
+
# censored-mid-bucket exposure is dropped: only fully observed
|
| 243 |
+
# buckets contribute negatives
|
| 244 |
+
in_bucket = (dur >= hi) | died_here
|
| 245 |
+
rows.append(X[in_bucket])
|
| 246 |
+
ys.append(died_here[in_bucket])
|
| 247 |
+
ks.append(np.full(in_bucket.sum(), k))
|
| 248 |
+
Xpp = np.vstack(rows)
|
| 249 |
+
kpp = np.concatenate(ks)
|
| 250 |
+
Xpp = np.column_stack([Xpp] + [(kpp == k).astype(float)
|
| 251 |
+
for k in range(1, self.K)])
|
| 252 |
+
self.clf = make_pipeline(SimpleImputer(strategy='median'),
|
| 253 |
+
StandardScaler(),
|
| 254 |
+
LogisticRegression(max_iter=2000, C=1.0))
|
| 255 |
+
self.clf.fit(Xpp, np.concatenate(ys))
|
| 256 |
+
|
| 257 |
+
dead = train_censored[(train_censored['event'] == 1) &
|
| 258 |
+
(train_censored['duration'] <= WINDOW_DAYS)]
|
| 259 |
+
self.days = DayQuantiles().fit(dead[FEATURES], dead['duration'])
|
| 260 |
+
return self
|
| 261 |
+
|
| 262 |
+
def predict(self, rows):
|
| 263 |
+
X = rows[FEATURES].values
|
| 264 |
+
n = len(rows)
|
| 265 |
+
haz = np.empty((n, self.K))
|
| 266 |
+
for k in range(self.K):
|
| 267 |
+
dummies = [(np.full(n, k) == j).astype(float) for j in range(1, self.K)]
|
| 268 |
+
haz[:, k] = self.clf.predict_proba(np.column_stack([X] + dummies))[:, 1]
|
| 269 |
+
surv = np.cumprod(1.0 - haz, axis=1)
|
| 270 |
+
p42 = 1.0 - surv[:, -1]
|
| 271 |
+
out = self.days.predict(rows[FEATURES])
|
| 272 |
+
out['p42'] = p42
|
| 273 |
+
# override day quantiles with the hazard model's own conditional CDF
|
| 274 |
+
cdf = (1.0 - surv) / np.maximum(p42[:, None], 1e-12)
|
| 275 |
+
ends = self.BUCKET * np.arange(1, self.K + 1)
|
| 276 |
+
for q in DAY_QUANTILES:
|
| 277 |
+
day = np.array([np.interp(q, np.concatenate([[0.0], cdf[i]]),
|
| 278 |
+
np.concatenate([[0.0], ends]))
|
| 279 |
+
for i in range(n)])
|
| 280 |
+
out[f'day_q{q}'] = np.clip(day, 0, WINDOW_DAYS)
|
| 281 |
+
return out
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def determined_labels(train_censored):
|
| 286 |
+
"""Pairs whose dies42 label is already fully determined at the cut:
|
| 287 |
+
survived the whole window (duration >= 42) or died inside it. Recovers
|
| 288 |
+
open-window positives that training_pairs() throws away."""
|
| 289 |
+
neg = train_censored['duration'] >= WINDOW_DAYS
|
| 290 |
+
pos = (train_censored['event'] == 1) & (train_censored['duration'] <= WINDOW_DAYS)
|
| 291 |
+
sub = train_censored[neg | pos].copy()
|
| 292 |
+
sub['dies42'] = ((sub['event'] == 1) &
|
| 293 |
+
(sub['duration'] <= WINDOW_DAYS)).astype(int)
|
| 294 |
+
sub['days_to_eol'] = sub['duration']
|
| 295 |
+
return sub
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class LogBagOpen:
|
| 299 |
+
"""logbag trained on the determined-label set (closed windows + open-window
|
| 300 |
+
deaths observed before the origin)."""
|
| 301 |
+
|
| 302 |
+
def fit(self, train_censored):
|
| 303 |
+
from sklearn.ensemble import BaggingClassifier
|
| 304 |
+
train = determined_labels(train_censored)
|
| 305 |
+
X, y = train[FEATURES], train['dies42']
|
| 306 |
+
base = make_pipeline(SimpleImputer(strategy='median'),
|
| 307 |
+
StandardScaler(),
|
| 308 |
+
LogisticRegression(max_iter=2000, C=1.0))
|
| 309 |
+
self.clf = BaggingClassifier(base, n_estimators=15, random_state=0)
|
| 310 |
+
self.clf.fit(X, y)
|
| 311 |
+
dying = train[train['dies42'] == 1]
|
| 312 |
+
self.days = DayQuantiles().fit(dying[FEATURES], dying['days_to_eol'])
|
| 313 |
+
return self
|
| 314 |
+
|
| 315 |
+
def predict(self, rows):
|
| 316 |
+
X = rows[FEATURES]
|
| 317 |
+
out = self.days.predict(X)
|
| 318 |
+
out['p42'] = self.clf.predict_proba(X)[:, 1]
|
| 319 |
+
return out
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class BlendDH:
|
| 323 |
+
"""Mean of LogBagOpen and DiscreteHazard p42: same features, but different
|
| 324 |
+
training sets and likelihoods, so their errors decorrelate."""
|
| 325 |
+
|
| 326 |
+
def fit(self, train_censored):
|
| 327 |
+
self.a = LogBagOpen().fit(train_censored)
|
| 328 |
+
self.b = DiscreteHazard().fit(train_censored)
|
| 329 |
+
return self
|
| 330 |
+
|
| 331 |
+
def predict(self, rows):
|
| 332 |
+
out = self.a.predict(rows)
|
| 333 |
+
out['p42'] = 0.5 * (out['p42'] + self.b.predict(rows)['p42'])
|
| 334 |
+
return out
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class WeightedBagLogistic:
|
| 338 |
+
"""Bagged logistic with recency-weighted samples: pairs from recent origins
|
| 339 |
+
count more, on the theory that fleet composition and degradation mix drift."""
|
| 340 |
+
|
| 341 |
+
def __init__(self, half_life=180.0, n_estimators=15):
|
| 342 |
+
self.half_life = half_life
|
| 343 |
+
self.n_estimators = n_estimators
|
| 344 |
+
|
| 345 |
+
def fit(self, train):
|
| 346 |
+
X, y = train[FEATURES], train['dies42']
|
| 347 |
+
age = (train['origin'].max() - train['origin']).dt.days.values
|
| 348 |
+
w = 0.5 ** (age / self.half_life)
|
| 349 |
+
rng = np.random.RandomState(0)
|
| 350 |
+
self.models = []
|
| 351 |
+
n = len(X)
|
| 352 |
+
for _ in range(self.n_estimators):
|
| 353 |
+
idx = rng.randint(0, n, n)
|
| 354 |
+
m = make_pipeline(SimpleImputer(strategy='median'),
|
| 355 |
+
StandardScaler(),
|
| 356 |
+
LogisticRegression(max_iter=2000, C=1.0))
|
| 357 |
+
m.fit(X.iloc[idx], y.iloc[idx],
|
| 358 |
+
logisticregression__sample_weight=w[idx])
|
| 359 |
+
self.models.append(m)
|
| 360 |
+
dying = train[train['dies42'] == 1]
|
| 361 |
+
self.days = DayQuantiles().fit(dying[FEATURES], dying['days_to_eol'])
|
| 362 |
+
return self
|
| 363 |
+
|
| 364 |
+
def predict(self, rows):
|
| 365 |
+
X = rows[FEATURES]
|
| 366 |
+
out = self.days.predict(X)
|
| 367 |
+
out['p42'] = np.mean([m.predict_proba(X)[:, 1] for m in self.models], axis=0)
|
| 368 |
+
return out
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class BlendRUL:
|
| 373 |
+
"""Mean of logbag and gbm probabilities: linear and tree models miss
|
| 374 |
+
different deaths; averaging keeps sum(p42) meaningful for topsum."""
|
| 375 |
+
|
| 376 |
+
def fit(self, train):
|
| 377 |
+
self.a = SklearnRUL('logbag').fit(train)
|
| 378 |
+
try:
|
| 379 |
+
self.b = SklearnRUL('gbm').fit(train)
|
| 380 |
+
except ValueError: # hist-GBM needs more rows than the earliest origins have
|
| 381 |
+
self.b = None
|
| 382 |
+
return self
|
| 383 |
+
|
| 384 |
+
def predict(self, rows):
|
| 385 |
+
out = self.a.predict(rows)
|
| 386 |
+
if self.b is not None:
|
| 387 |
+
out['p42'] = 0.5 * (out['p42'] + self.b.predict(rows)['p42'])
|
| 388 |
+
return out
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class LogBagC:
|
| 392 |
+
"""logbag with a non-default inverse regularization C."""
|
| 393 |
+
|
| 394 |
+
def __init__(self, C):
|
| 395 |
+
self.C = C
|
| 396 |
+
|
| 397 |
+
def fit(self, train):
|
| 398 |
+
from sklearn.ensemble import BaggingClassifier
|
| 399 |
+
X, y = train[FEATURES], train['dies42']
|
| 400 |
+
base = make_pipeline(SimpleImputer(strategy='median'),
|
| 401 |
+
StandardScaler(),
|
| 402 |
+
LogisticRegression(max_iter=2000, C=self.C))
|
| 403 |
+
self.clf = BaggingClassifier(base, n_estimators=15, random_state=0)
|
| 404 |
+
self.clf.fit(X, y)
|
| 405 |
+
dying = train[train['dies42'] == 1]
|
| 406 |
+
self.days = DayQuantiles().fit(dying[FEATURES], dying['days_to_eol'])
|
| 407 |
+
return self
|
| 408 |
+
|
| 409 |
+
def predict(self, rows):
|
| 410 |
+
X = rows[FEATURES]
|
| 411 |
+
out = self.days.predict(X)
|
| 412 |
+
out['p42'] = self.clf.predict_proba(X)[:, 1]
|
| 413 |
+
return out
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class LogBagFeats:
|
| 418 |
+
"""logbag with extra feature columns (aux usage-dynamics table)."""
|
| 419 |
+
|
| 420 |
+
def __init__(self, extra):
|
| 421 |
+
self.feats = FEATURES + extra
|
| 422 |
+
|
| 423 |
+
def fit(self, train):
|
| 424 |
+
from sklearn.ensemble import BaggingClassifier
|
| 425 |
+
X, y = train[self.feats], train['dies42']
|
| 426 |
+
base = make_pipeline(SimpleImputer(strategy='median'),
|
| 427 |
+
StandardScaler(),
|
| 428 |
+
LogisticRegression(max_iter=2000, C=1.0))
|
| 429 |
+
self.clf = BaggingClassifier(base, n_estimators=15, random_state=0)
|
| 430 |
+
self.clf.fit(X, y)
|
| 431 |
+
dying = train[train['dies42'] == 1]
|
| 432 |
+
self.days = DayQuantiles().fit(dying[FEATURES], dying['days_to_eol'])
|
| 433 |
+
return self
|
| 434 |
+
|
| 435 |
+
def predict(self, rows):
|
| 436 |
+
out = self.days.predict(rows[FEATURES])
|
| 437 |
+
out['p42'] = self.clf.predict_proba(rows[self.feats])[:, 1]
|
| 438 |
+
return out
|
| 439 |
+
|
| 440 |
+
|
| 441 |
MODELS = {
|
| 442 |
'rank-v': RankVoltage,
|
| 443 |
'logistic': lambda: SklearnRUL('logistic'),
|
|
|
|
| 445 |
'logbag': lambda: SklearnRUL('logbag'),
|
| 446 |
'gbm': lambda: SklearnRUL('gbm'),
|
| 447 |
'aft': WeibullAFT,
|
| 448 |
+
'logbag_rw120': lambda: WeightedBagLogistic(half_life=120.0),
|
| 449 |
+
'logbag_rw240': lambda: WeightedBagLogistic(half_life=240.0),
|
| 450 |
+
'dthaz': DiscreteHazard,
|
| 451 |
+
'blend': BlendRUL,
|
| 452 |
+
'logbag_c03': lambda: LogBagC(0.3),
|
| 453 |
+
'logbag_c3': lambda: LogBagC(3.0),
|
| 454 |
+
'logbag_c01': lambda: LogBagC(0.1),
|
| 455 |
+
'logbag_open': LogBagOpen,
|
| 456 |
+
'blend_dh': BlendDH,
|
| 457 |
+
'logbag_aux': lambda: LogBagFeats(['rng_90', 'vstd_30', 'rng_ratio', 'gap_max_60']),
|
| 458 |
+
'logbag_aux2': lambda: LogBagFeats(['rng_30', 'rng_90', 'vstd_30']),
|
| 459 |
}
|
| 460 |
|
| 461 |
|
| 462 |
+
def resolve_model(name):
|
| 463 |
+
"""'logbag:bags=30,q6=1' -> SklearnRUL variant; plain names via MODELS."""
|
| 464 |
+
if name in MODELS:
|
| 465 |
+
return MODELS[name]
|
| 466 |
+
return lambda: SklearnRUL(name)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
# ------------------------------------------------------------------------- planners
|
| 470 |
|
| 471 |
def assemble(selected_days, locations, start_time):
|
|
|
|
| 708 |
|
| 709 |
|
| 710 |
def optimize_days(groups, curves, locations, travel_hours, settings, start_time,
|
| 711 |
+
restarts=None, iters=None):
|
| 712 |
+
restarts = restarts if restarts is not None else optimize_days.restarts
|
| 713 |
+
iters = iters if iters is not None else optimize_days.iters
|
| 714 |
"""
|
| 715 |
Local search over building-group visit days: shift moves, merge moves (jump a
|
| 716 |
group onto another group's day), and deterministic random restarts.
|
|
|
|
| 758 |
return best
|
| 759 |
|
| 760 |
|
| 761 |
+
optimize_days.restarts = 2
|
| 762 |
+
optimize_days.iters = 60
|
| 763 |
+
|
| 764 |
+
|
| 765 |
def plan_ecroute(pred, included, locations, start_time, day_q,
|
| 766 |
travel_costs=None, settings=None, margin=None):
|
| 767 |
"""
|
|
|
|
| 841 |
plan_tsroute.floor_day = 0
|
| 842 |
plan_tsroute.p_conf = 0.5
|
| 843 |
|
| 844 |
+
def plan_tspig(pred, included, locations, start_time, day_q,
|
| 845 |
+
travel_costs=None, settings=None):
|
| 846 |
+
"""
|
| 847 |
+
tsroute + exact-marginal membership repair. After the day search:
|
| 848 |
+
drop pass - remove any included battery whose expected timing benefit at its
|
| 849 |
+
assigned day is worse than parking, counting the exact mobility
|
| 850 |
+
saving (a group that empties refunds its whole trip);
|
| 851 |
+
add pass - piggyback parked batteries onto buildings already being visited
|
| 852 |
+
when benefit at that day exceeds the exact mobility delta
|
| 853 |
+
(usually just battery-handling time), then whole new building
|
| 854 |
+
groups when their pooled benefit pays for the trip.
|
| 855 |
+
Inclusion thereby becomes routing-aware instead of count-only.
|
| 856 |
+
"""
|
| 857 |
+
n = int(round(plan_tspig.alpha * pred['p42'].sum()))
|
| 858 |
+
chosen = pred['p42'].nlargest(n).index
|
| 859 |
+
curves_np, park_np = cost_curves(pred, locations, start_time)
|
| 860 |
+
curves_all = pd.DataFrame(curves_np, index=pred.index)
|
| 861 |
+
park = pd.Series(park_np, index=pred.index)
|
| 862 |
+
loc = locations.set_index('battery')
|
| 863 |
+
bldg_all, room_all = loc['building'], loc['room']
|
| 864 |
+
travel_hours = travel_costs.set_index(['from', 'to'])['hours'].unstack()
|
| 865 |
+
|
| 866 |
+
if len(chosen) == 0:
|
| 867 |
+
return assemble(pd.Series(dtype='datetime64[ns]'), locations, start_time)
|
| 868 |
+
|
| 869 |
+
curves = curves_all.loc[chosen]
|
| 870 |
+
bldg = bldg_all.reindex(chosen)
|
| 871 |
+
groups = {g: sorted(m.index, key=lambda b: room_all.get(b, ''))
|
| 872 |
+
for g, m in curves.groupby(bldg)}
|
| 873 |
+
day_of = optimize_days(groups, curves, locations, travel_hours,
|
| 874 |
+
settings, start_time)
|
| 875 |
+
|
| 876 |
+
def mobility(gs, days):
|
| 877 |
+
day_batteries = {}
|
| 878 |
+
for g in sorted(days, key=lambda g: (days[g], g)):
|
| 879 |
+
if gs.get(g):
|
| 880 |
+
day_batteries.setdefault(days[g], []).extend(gs[g])
|
| 881 |
+
return mobility_cost(day_batteries, locations, travel_hours,
|
| 882 |
+
settings, start_time)
|
| 883 |
+
|
| 884 |
+
cur_mob = mobility(groups, day_of)
|
| 885 |
+
in_plan = set().union(*groups.values())
|
| 886 |
+
|
| 887 |
+
for _ in range(4):
|
| 888 |
+
improved = False
|
| 889 |
+
# drop pass
|
| 890 |
+
for g in list(groups):
|
| 891 |
+
for b in list(groups[g]):
|
| 892 |
+
trial = dict(groups, **{g: [x for x in groups[g] if x != b]})
|
| 893 |
+
dm = mobility(trial, day_of) - cur_mob
|
| 894 |
+
if park.at[b] - curves_all.at[b, day_of[g]] + dm < -1e-9:
|
| 895 |
+
groups, cur_mob = trial, cur_mob + dm
|
| 896 |
+
in_plan.discard(b)
|
| 897 |
+
improved = True
|
| 898 |
+
# piggyback adds within visited buildings
|
| 899 |
+
active = {g for g in groups if groups[g]}
|
| 900 |
+
cands = [b for b in pred.index
|
| 901 |
+
if b not in in_plan and bldg_all.get(b) in active]
|
| 902 |
+
for b in sorted(cands, key=lambda b: -pred.at[b, 'p42']):
|
| 903 |
+
g = bldg_all.get(b)
|
| 904 |
+
if not groups.get(g):
|
| 905 |
+
continue
|
| 906 |
+
trial = dict(groups, **{g: sorted(groups[g] + [b],
|
| 907 |
+
key=lambda x: room_all.get(x, ''))})
|
| 908 |
+
dm = mobility(trial, day_of) - cur_mob
|
| 909 |
+
if curves_all.at[b, day_of[g]] - park.at[b] + dm < -1e-9:
|
| 910 |
+
groups, cur_mob = trial, cur_mob + dm
|
| 911 |
+
in_plan.add(b)
|
| 912 |
+
improved = True
|
| 913 |
+
# whole new building groups whose pooled benefit pays for the trip
|
| 914 |
+
outside = pred.index.difference(list(in_plan))
|
| 915 |
+
for g, members in bldg_all.reindex(outside).groupby(bldg_all.reindex(outside)):
|
| 916 |
+
if groups.get(g):
|
| 917 |
+
continue
|
| 918 |
+
gain = park.reindex(members.index) - curves_all.loc[members.index].min(axis=1)
|
| 919 |
+
keep = gain[gain > 0].index
|
| 920 |
+
if len(keep) == 0:
|
| 921 |
+
continue
|
| 922 |
+
day = int(curves_all.loc[keep].sum(axis=0).values.argmin())
|
| 923 |
+
trial = dict(groups, **{g: sorted(keep, key=lambda x: room_all.get(x, ''))})
|
| 924 |
+
tdays = dict(day_of, **{g: day})
|
| 925 |
+
dm = mobility(trial, tdays) - cur_mob
|
| 926 |
+
delta = (curves_all.loc[keep, day] - park.reindex(keep)).sum() + dm
|
| 927 |
+
if delta < -1e-9:
|
| 928 |
+
groups, day_of, cur_mob = trial, tdays, cur_mob + dm
|
| 929 |
+
in_plan.update(keep)
|
| 930 |
+
improved = True
|
| 931 |
+
if not improved:
|
| 932 |
+
break
|
| 933 |
+
|
| 934 |
+
groups = {g: bs for g, bs in groups.items() if bs}
|
| 935 |
+
if not groups:
|
| 936 |
+
return assemble(pd.Series(dtype='datetime64[ns]'), locations, start_time)
|
| 937 |
+
# final day re-optimization with the repaired membership
|
| 938 |
+
day_of = optimize_days(groups, curves_all.loc[sorted(in_plan)], locations,
|
| 939 |
+
travel_hours, settings, start_time)
|
| 940 |
+
offs, idx = [], []
|
| 941 |
+
for g, bs in groups.items():
|
| 942 |
+
for b in bs:
|
| 943 |
+
idx.append(b)
|
| 944 |
+
offs.append(float(day_of[g]))
|
| 945 |
+
days = start_time + pd.to_timedelta(offs, unit='D')
|
| 946 |
+
return assemble(pd.Series(days, index=idx), locations, start_time)
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
plan_tspig.alpha = 0.8
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
def plan_tspig2(pred, included, locations, start_time, day_q,
|
| 953 |
+
travel_costs=None, settings=None):
|
| 954 |
+
"""
|
| 955 |
+
Rank-gated piggyback: run tsroute on the usual top-N (alpha), then extend
|
| 956 |
+
inclusion to batteries ranked within alpha2 * sum(p42) whose building is
|
| 957 |
+
already visited, scheduling them on that building's existing day. Extra
|
| 958 |
+
inclusions are chosen by rank (scale-free), not expected value; only the
|
| 959 |
+
mobility context decides whether the insurance is cheap enough.
|
| 960 |
+
"""
|
| 961 |
+
n = int(round(plan_tspig2.alpha * pred['p42'].sum()))
|
| 962 |
+
chosen = pred['p42'].nlargest(n).index
|
| 963 |
+
if len(chosen) == 0:
|
| 964 |
+
return assemble(pd.Series(dtype='datetime64[ns]'), locations, start_time)
|
| 965 |
+
|
| 966 |
+
curves_np, _ = cost_curves(pred, locations, start_time)
|
| 967 |
+
curves_all = pd.DataFrame(curves_np, index=pred.index)
|
| 968 |
+
loc = locations.set_index('battery')
|
| 969 |
+
bldg_all, room_all = loc['building'], loc['room']
|
| 970 |
+
travel_hours = travel_costs.set_index(['from', 'to'])['hours'].unstack()
|
| 971 |
+
|
| 972 |
+
curves = curves_all.loc[chosen]
|
| 973 |
+
bldg = bldg_all.reindex(chosen)
|
| 974 |
+
groups = {g: sorted(m.index, key=lambda b: room_all.get(b, ''))
|
| 975 |
+
for g, m in curves.groupby(bldg)}
|
| 976 |
+
day_of = optimize_days(groups, curves, locations, travel_hours,
|
| 977 |
+
settings, start_time)
|
| 978 |
+
|
| 979 |
+
n2 = int(round(plan_tspig2.alpha2 * pred['p42'].sum()))
|
| 980 |
+
extras = pred['p42'].nlargest(n2).index.difference(chosen)
|
| 981 |
+
offs, idx = [], []
|
| 982 |
+
for g, bs in groups.items():
|
| 983 |
+
for b in bs:
|
| 984 |
+
idx.append(b); offs.append(float(day_of[g]))
|
| 985 |
+
for b in extras:
|
| 986 |
+
g = bldg_all.get(b)
|
| 987 |
+
if g in day_of:
|
| 988 |
+
idx.append(b); offs.append(float(day_of[g]))
|
| 989 |
+
days = start_time + pd.to_timedelta(offs, unit='D')
|
| 990 |
+
return assemble(pd.Series(days, index=idx), locations, start_time)
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
plan_tspig2.alpha = 0.8
|
| 994 |
+
plan_tspig2.alpha2 = 1.3
|
| 995 |
+
|
| 996 |
+
PLANNERS ={'onepd': plan_onepd, 'sched': plan_sched, 'batch': plan_batch,
|
| 997 |
'expcost': plan_expcost, 'topsum': plan_topsum,
|
| 998 |
+
'ecday': plan_ecday, 'ecroute': plan_ecroute, 'tsroute': plan_tsroute,
|
| 999 |
+
'tspig': plan_tspig, 'tspig2': plan_tspig2}
|
| 1000 |
|
| 1001 |
|
| 1002 |
# ------------------------------------------------------------------------ harness
|
|
|
|
| 1028 |
preds = {}
|
| 1029 |
for model_name in {c['model'] for c in configs}:
|
| 1030 |
if (model_name, idx) not in fitted:
|
| 1031 |
+
factory = resolve_model(model_name)
|
| 1032 |
+
if model_name in ('aft', 'dthaz', 'logbag_open', 'blend_dh'):
|
| 1033 |
train = censored_pairs(table, origin_time)
|
| 1034 |
else:
|
| 1035 |
train = training_pairs(table, origin_time)
|
|
|
|
| 1043 |
if cfg['planner'] == 'ecroute':
|
| 1044 |
PLANNERS['ecroute'].margin = cfg['p_star'] or 1.0 # p_star carries margin
|
| 1045 |
PLANNERS['ecroute'].blend = cfg.get('blend', 0.0)
|
| 1046 |
+
if cfg['planner'] == 'tspig':
|
| 1047 |
+
PLANNERS['tspig'].alpha = cfg['p_star'] or 0.8
|
| 1048 |
+
if cfg['planner'] == 'tspig2':
|
| 1049 |
+
PLANNERS['tspig2'].alpha = cfg['p_star'] or 0.8
|
| 1050 |
+
PLANNERS['tspig2'].alpha2 = cfg.get('alpha2', 1.3)
|
| 1051 |
if cfg['planner'] == 'tsroute':
|
| 1052 |
PLANNERS['tsroute'].alpha = cfg['p_star'] or 0.8 # p_star carries alpha
|
| 1053 |
PLANNERS['tsroute'].p_be = cfg.get('p_be', 0.0)
|
| 1054 |
PLANNERS['tsroute'].floor_day = cfg.get('floor_day', 0)
|
| 1055 |
PLANNERS['tsroute'].p_conf = cfg.get('p_conf', 0.5)
|
| 1056 |
+
global EMERGENCY_DAY
|
| 1057 |
+
EMERGENCY_DAY = cfg.get('emergency_day', WINDOW_DAYS + 3)
|
| 1058 |
+
optimize_days.restarts = int(cfg.get('restarts', 2))
|
| 1059 |
+
optimize_days.iters = int(cfg.get('iters', 60))
|
| 1060 |
included = pred.index[pred['p42'] >= cfg['p_star']]
|
| 1061 |
kwargs = {}
|
| 1062 |
+
if cfg['planner'] in ('ecroute', 'tsroute', 'tspig', 'tspig2'):
|
| 1063 |
kwargs = dict(travel_costs=ctx['travel_costs'],
|
| 1064 |
settings=ctx['settings'])
|
| 1065 |
plan = PLANNERS[cfg['planner']](pred, included, ctx['locs'],
|
|
|
|
| 1091 |
def summarize(df, label):
|
| 1092 |
df['name'] = (df['model'] + '/' + df['planner'] + '/p' +
|
| 1093 |
df['p_star'].astype(str) + '/q' + df['day_q'].astype(str))
|
| 1094 |
+
for key, tag in [('blend', 'b'), ('p_be', 'be'), ('floor_day', 'f'), ('p_conf', 'c'),
|
| 1095 |
+
('alpha2', 'a2'), ('emergency_day', 'e'), ('restarts', 'r'),
|
| 1096 |
+
('iters', 'i')]:
|
| 1097 |
if key in df.columns and df[key].nunique(dropna=False) > 1:
|
| 1098 |
df['name'] += '/' + tag + df[key].fillna(0).astype(str)
|
| 1099 |
mean = df.groupby('name')['total_cost'].agg(['mean', 'std']).sort_values('mean')
|
|
|
|
| 1105 |
def main():
|
| 1106 |
dataset_path = Path(os.environ.get('BATTERYSWAP_DATASET_PATH', 'dataset'))
|
| 1107 |
table = load_features(dataset_path)
|
| 1108 |
+
try:
|
| 1109 |
+
from batteryswap_example.aux_features import load as load_aux
|
| 1110 |
+
table = table.merge(load_aux(dataset_path), on=['device_id', 'origin_idx'],
|
| 1111 |
+
how='left')
|
| 1112 |
+
except FileNotFoundError:
|
| 1113 |
+
pass
|
| 1114 |
ctx = load_context(dataset_path)
|
| 1115 |
|
| 1116 |
phase = sys.argv[1] if len(sys.argv) > 1 else 'dev'
|