Syntrex commited on
Commit
b221bf6
·
verified ·
1 Parent(s): 5556f61

Update SQL

Browse files
Files changed (1) hide show
  1. SQL +221 -463
SQL CHANGED
@@ -1,463 +1,221 @@
1
- Batch 13 — Opportunity Model + Arsenal Drift + Full Debug Dashboard
2
-
3
- Context
4
-
5
- Three upgrades to the upcoming-game simulator pipeline:
6
- 1. Opportunity Model — PA-based scaling using lineup slot, team total, and pitcher quality (SwStr/CSW/Ball%)
7
- 2. Arsenal Drift Layer — Short-term pitcher changes using existing rolling signals, additive, anti-double-count vs rolling layer
8
- 3. Full Debug Dashboard — Replace the 1000-line debug expander in Dashboard with a proper "Debug" nav page
9
-
10
- All changes are upcoming-only. Live engine (engine/live_game_engine.py, simulation/pitch_simulator.py) untouched.
11
-
12
- ---
13
- Pre-flight: Critical Findings from Codebase Exploration
14
-
15
- 1. swstr_rate, csw_rate, ball_rate do NOT exist in pitcher_row — must be added to build_pitcher_feature_row() using the description column (already in normalized
16
- statcast). Pattern exists in batter_zone_model.py:146 and batter_arsenal_model.py:57.
17
- 2. lineup_slot (int 1-9) is NOT in game_row — batting order position is not fetched. Function must accept None; when None, use PA_MAP baseline 4.3 (equivalent to
18
- slot 5). Team total and pitcher quality still apply.
19
- 3. team_total is NOT in game_row — will be None until odds integration adds it. Function handles None gracefully (skip that step).
20
- 4. models/opportunity_model.py already exists with estimate_plate_appearance_probability(outs, lineup_distance) used in analytics/recommendation_engine.py. The
21
- new compute_opportunity_adjustment() is a different function (full-game PA scaling vs. per-inning live context). Both coexist.
22
- 5. Debug expander bounds — with st.expander("Debug: raw schedule, scores"): at line 2657, ends at line 3682. render_live_prop_odds_debug_panel(live_games) at
23
- line 3683 is OUTSIDE and stays in Dashboard.
24
- 6. Existing adjustment order in simulator (lines in live_fair_simulator_v3.py):
25
- - Blended pitch (242) → Zone (270) → Family Zone (304) → Arsenal (348) → Pulled contact (382) → Env (431) → Platoon (440) → Trajectory (468) → Rolling (496) →
26
- simulate (538)
27
- - New layers insert: Rolling (496) → Opportunity multiplier → Drift additive → simulate
28
-
29
- ---
30
- Files Modified / Created
31
-
32
- ┌──────────────────────────────────┬───────────────────────────────────────────────────────────────────────────────────────┐
33
- │ File │ Action │
34
- ├──────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────┤
35
- │ models/pitcher_adjustment.py │ ADD swstr_rate, csw_rate, ball_rate to build_pitcher_feature_row() │
36
- ├──────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────┤
37
- │ models/opportunity_model.py │ ADD compute_opportunity_adjustment() to existing file │
38
- ├──────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────┤
39
- │ models/arsenal_drift_model.py │ CREATE new file │
40
- ├──────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────┤
41
- │ models/live_fair_simulator_v3.py │ ADD imports, integrate opportunity + drift, ADD baseline snapshot + new output fields │
42
- ├──────────────────────────────────┼──────────────────────────────────────────��────────────────────────────────────────────┤
43
- │ visualization/debug_page.py │ CREATE new file with render_debug() │
44
- ├──────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────┤
45
- │ app.py │ REMOVE debug expander (lines 2657–3682), ADD "Debug" nav + import │
46
- └──────────────────────────────────┴───────────────────────────────────────────────────────────────────────────────────────┘
47
-
48
- ---
49
- TASK 1 — Pitcher Quality Fields
50
-
51
- File: models/pitcher_adjustment.py
52
-
53
- After computing the existing fields (after avg_launch_angle_allowed), add:
54
-
55
- # Pitch-level rates from description column
56
- swstr_rate = None
57
- csw_rate = None
58
- ball_rate = None
59
- if "description" in df.columns and len(df) >= 10:
60
- desc = df["description"].astype(str).str.strip().str.lower()
61
- total = len(desc)
62
- swstr_mask = desc.isin({"swinging_strike", "swinging_strike_blocked"})
63
- cs_mask = desc == "called_strike"
64
- ball_mask = desc.isin({"ball", "blocked_ball", "intent_ball", "pitchout"})
65
- swstr_rate = float(swstr_mask.sum() / total)
66
- csw_rate = float((swstr_mask | cs_mask).sum() / total)
67
- ball_rate = float(ball_mask.sum() / total)
68
-
69
- Add to return dict: "swstr_rate": swstr_rate, "csw_rate": csw_rate, "ball_rate": ball_rate
70
- Also add these three keys to the empty-return dicts (lines 57–76 and 113–132) as None.
71
-
72
- ---
73
- TASK 2 — Opportunity Model
74
-
75
- File: models/opportunity_model.py — ADD new function below the existing estimate_plate_appearance_probability().
76
-
77
- PA_MAP = {1: 4.7, 2: 4.6, 3: 4.5, 4: 4.4, 5: 4.3, 6: 4.2, 7: 4.1, 8: 4.0, 9: 3.9}
78
- _PA_BASELINE = 4.3
79
-
80
- def compute_opportunity_adjustment(
81
- lineup_slot: int | None,
82
- team_total: float | None,
83
- pitcher_row: dict | None,
84
- ) -> dict:
85
-
86
- Step 1 — Base PA:
87
- pa = PA_MAP.get(int(lineup_slot), _PA_BASELINE) if lineup_slot is not None else _PA_BASELINE
88
-
89
- Step 2 — Team total:
90
- if team_total is not None:
91
- if team_total > 5.5: pa += 0.15
92
- elif team_total < 3.5: pa -= 0.15
93
-
94
- Step 3 — Pitcher quality (SwStr/CSW/Ball):
95
- # Extract from pitcher_row (None-safe)
96
- swstr = pitcher_row.get("swstr_rate") if pitcher_row else None
97
- csw = pitcher_row.get("csw_rate") if pitcher_row else None
98
- ball = pitcher_row.get("ball_rate") if pitcher_row else None
99
-
100
- if all(v is not None for v in [swstr, csw, ball]):
101
- # 3A SwStr score
102
- if swstr < 0.08: swstr_score = +0.4
103
- elif swstr < 0.10: swstr_score = +0.2
104
- elif swstr < 0.12: swstr_score = 0.0
105
- elif swstr < 0.14: swstr_score = -0.3
106
- else: swstr_score = -0.5
107
- # 3B CSW score
108
- if csw < 0.26: csw_score = +0.3
109
- elif csw < 0.28: csw_score = +0.1
110
- elif csw < 0.30: csw_score = 0.0
111
- elif csw < 0.32: csw_score = -0.2
112
- else: csw_score = -0.4
113
- # 3C Ball score
114
- if ball < 0.32: ball_score = -0.3
115
- elif ball < 0.35: ball_score = -0.1
116
- elif ball < 0.38: ball_score = 0.0
117
- elif ball < 0.41: ball_score = +0.2
118
- else: ball_score = +0.4
119
- # 3D Ratio score
120
- ratio = swstr / max(ball, 0.01)
121
- if ratio > 0.40: ratio_score = -0.4
122
- elif ratio > 0.30: ratio_score = -0.2
123
- elif ratio > 0.22: ratio_score = 0.0
124
- elif ratio > 0.15: ratio_score = +0.2
125
- else: ratio_score = +0.4
126
- # 3E Combine
127
- quality_score = _clamp(
128
- swstr_score*0.35 + csw_score*0.30 + ball_score*0.20 + ratio_score*0.15,
129
- -1.0, 1.0
130
- )
131
- pa_multiplier = _clamp(1.0 + quality_score * 0.25, 0.85, 1.15)
132
- opportunity_reason = f"swstr={swstr:.3f}|csw={csw:.3f}|ball={ball:.3f}"
133
- else:
134
- quality_score = 0.0
135
- pa_multiplier = 1.0
136
- opportunity_reason = "pitcher_quality_missing"
137
-
138
- Output:
139
- return {
140
- "expected_pa": round(pa, 3),
141
- "pa_multiplier": round(pa_multiplier, 4),
142
- "pitcher_quality_score": round(quality_score, 4),
143
- "opportunity_reason": opportunity_reason,
144
- # Traceability: expose what was and wasn't available
145
- "lineup_slot_used": lineup_slot, # None if batting order not available
146
- "team_total_used": team_total, # None if not in game_row
147
- "opportunity_mode": (
148
- "full" if (lineup_slot is not None and team_total is not None)
149
- else "pitcher_quality_only" if all(v is not None for v in [swstr, csw, ball])
150
- else "slot_only" if lineup_slot is not None
151
- else "baseline_only"
152
- ),
153
- }
154
-
155
- Add _clamp helper to the file (or import from rolling_form_model — prefer self-contained).
156
-
157
- ---
158
- TASK 3 — Arsenal Drift Layer
159
-
160
- File: models/arsenal_drift_model.py — NEW
161
-
162
- def compute_arsenal_drift_adjustment(
163
- pitcher_roll: dict,
164
- pitcher_row: dict,
165
- rolling_reason_tags: str = "",
166
- ) -> dict:
167
-
168
- Deltas (recomputed from existing data, no new statcast queries):
169
- velo_delta = _safe_delta(pitcher_roll.get("pitcher_avg_release_speed_5g"), pitcher_row.get("avg_release_speed"))
170
- spin_delta = _safe_delta(pitcher_roll.get("pitcher_avg_release_spin_rate_5g"), pitcher_row.get("avg_release_spin_rate"))
171
- ev_delta = _safe_delta(pitcher_roll.get("pitcher_ev_allowed_5g"), pitcher_row.get("ev_allowed"))
172
- barrel_delta = _safe_delta(pitcher_roll.get("pitcher_barrel_rate_allowed_5g"), pitcher_row.get("barrel_rate_allowed"))
173
-
174
- Sample dampening (same _sample_scale pattern):
175
- n5 = int(pitcher_roll.get("pitcher_games_in_window_5g") or 0)
176
- confidence = float(pitcher_roll.get("pitcher_rolling_confidence") or 0.0)
177
- scale = _sample_scale(n5) * confidence # no double-application: confidence already includes match quality
178
-
179
- Overlap check (anti-double-count with rolling layer):
180
- rolling_tags = set(rolling_reason_tags.split("|")) if rolling_reason_tags else set()
181
- ev_overlap = "pitcher_ev_allowed_spiking" in rolling_tags # rolling already fired
182
- barrel_overlap = "pitcher_barrel_allowed_spiking" in rolling_tags
183
- velo_overlap = "pitcher_velo_decline_hard" in rolling_tags or "pitcher_velo_decline" in rolling_tags
184
-
185
- Scoring (drift_score ∈ [-0.5, +0.5]):
186
-
187
- ┌──────────────────────┬────────────┬───────┬────────────────────────┐
188
- │ Signal │ Threshold │ Score │ Overlap reduction │
189
- ├──────────────────────┼────────────┼───────┼────────────────────────┤
190
- │ Velo decline │ < -3 mph │ +0.25 │ 0 if velo_overlap │
191
- ├──────────────────────┼────────────┼───────┼────────────────────────┤
192
- │ Velo decline soft │ < -1.5 mph │ +0.15 │ 0 if velo_overlap │
193
- ├──────────────────────┼────────────┼───────┼────────────────────────┤
194
- │ Spin decline │ < -100 rpm │ +0.20 │ none (new signal) │
195
- ├──────────────────────┼────────────┼───────┼────────────────────────┤
196
- │ Spin surge │ > +100 rpm │ -0.15 │ none │
197
- ├──────────────────────┼────────────┼───────┼────────────────────────┤
198
- │ EV allowed spike │ > +2 mph │ +0.20 │ ×0.5 if ev_overlap │
199
- ├──────────────────────┼────────────┼───────┼────────────────────────┤
200
- │ Barrel allowed spike │ > +0.03 │ +0.25 │ ×0.5 if barrel_overlap │
201
- └──────────────────────┴────────────┴───────┴────────────────────────┘
202
-
203
- drift_score = _clamp(raw_drift_score * scale, -0.5, 0.5)
204
- hr_adj = round(drift_score * 0.006, 5)
205
- hit_adj = round(drift_score * 0.005, 5)
206
-
207
- Output:
208
- return {
209
- "arsenal_hr_adjustment": hr_adj,
210
- "arsenal_hit_adjustment": hit_adj,
211
- "arsenal_drift_score": round(drift_score, 4),
212
- "arsenal_reason_tags": "|".join(active_tags),
213
- }
214
-
215
- File includes local _safe_delta, _clamp, _sample_scale (copy from rolling_form_model.py — keep each model self-contained).
216
-
217
- ---
218
- TASK 4 — Simulator Integration
219
-
220
- File: models/live_fair_simulator_v3.py
221
-
222
- 4A — Imports (after line 35)
223
-
224
- from models.opportunity_model import compute_opportunity_adjustment
225
- from models.arsenal_drift_model import compute_arsenal_drift_adjustment
226
-
227
- 4B — Exact intermediate checkpoints for debug ladder
228
-
229
- After each adjustment block, snapshot the current probability values. These become the debug ladder. Add after batter_baseline = dict(batter_baseline) at line
230
- 242:
231
- _snap_baseline_hr = float(batter_baseline.get("hr_prob_base", 0.03) or 0.03)
232
- _snap_baseline_hit = float(batter_baseline.get("hit_prob_base", 0.15) or 0.15)
233
- _snap_baseline_tb2p = float(batter_baseline.get("tb2p_prob_base", 0.10) or 0.10)
234
-
235
- Then add a snapshot immediately after each adjustment block writes back to batter_baseline:
236
- - After zone block: _snap_after_zone_hr = float(batter_baseline["hr_prob_base"])
237
- - After family zone: _snap_after_family_zone_hr = ...
238
- - After arsenal matchup: _snap_after_arsenal_hr = ...
239
- - After env: _snap_after_env_hr = ...
240
- - After platoon: _snap_after_platoon_hr = ...
241
- - After trajectory: _snap_after_traj_hr = ...
242
- - After rolling: _snap_after_rolling_hr = ...
243
- - After opportunity: _snap_after_opportunity_hr = ...
244
- - After drift: _snap_after_drift_hr = ...
245
-
246
- Same pattern for _hit and _tb2p variants (total ~27 new local variables, surfaced in output dict).
247
-
248
- These are exact values — no reconstruction required. The debug ladder reads directly from these fields.
249
-
250
- 4C — Opportunity multiplier (AFTER rolling block, BEFORE simulate call ~line 538)
251
-
252
- # Batch 13: Opportunity adjustment (multiplicative, upcoming-only)
253
- try:
254
- opp_adj = compute_opportunity_adjustment(
255
- lineup_slot=None, # batting order not available in game_row currently
256
- team_total=game_row.get("team_total"),
257
- pitcher_row=pitcher_row,
258
- )
259
- except Exception:
260
- opp_adj = {"expected_pa": 4.3, "pa_multiplier": 1.0,
261
- "pitcher_quality_score": 0.0, "opportunity_reason": "error"}
262
-
263
- pa_mult = float(opp_adj.get("pa_multiplier", 1.0) or 1.0)
264
- batter_baseline["hit_prob_base"] = min(0.55, max(0.05,
265
- float(batter_baseline.get("hit_prob_base", 0.15) or 0.15) * pa_mult))
266
- batter_baseline["hr_prob_base"] = min(0.30, max(0.005,
267
- float(batter_baseline.get("hr_prob_base", 0.03) or 0.03) * pa_mult))
268
- batter_baseline["tb2p_prob_base"] = min(0.45, max(0.03,
269
- float(batter_baseline.get("tb2p_prob_base", 0.10) or 0.10) * pa_mult))
270
-
271
- 4D — Arsenal drift (AFTER opportunity, BEFORE simulate)
272
-
273
- # Batch 13: Arsenal drift adjustment (additive, upcoming-only)
274
- try:
275
- drift_adj = compute_arsenal_drift_adjustment(
276
- pitcher_roll=pitcher_rolling_row,
277
- pitcher_row=pitcher_row,
278
- rolling_reason_tags=rolling_adj.get("rolling_adjustment_reason_tags", ""),
279
- )
280
- except Exception:
281
- drift_adj = {"arsenal_hr_adjustment": 0.0, "arsenal_hit_adjustment": 0.0,
282
- "arsenal_drift_score": 0.0, "arsenal_reason_tags": ""}
283
-
284
- drift_hit = float(drift_adj.get("arsenal_hit_adjustment", 0.0) or 0.0)
285
- drift_hr = float(drift_adj.get("arsenal_hr_adjustment", 0.0) or 0.0)
286
- batter_baseline["hit_prob_base"] = min(0.55, max(0.05,
287
- float(batter_baseline.get("hit_prob_base", 0.15) or 0.15) + drift_hit))
288
- batter_baseline["hr_prob_base"] = min(0.30, max(0.005,
289
- float(batter_baseline.get("hr_prob_base", 0.03) or 0.03) + drift_hr))
290
-
291
- 4E — New output dict fields (in the return row dict, Batch 13 section)
292
-
293
- # Exact intermediate HR checkpoints for debug ladder (all logged in-place above)
294
- "snap_baseline_hr": _snap_baseline_hr,
295
- "snap_baseline_hit": _snap_baseline_hit,
296
- "snap_baseline_tb2p": _snap_baseline_tb2p,
297
- "snap_after_zone_hr": _snap_after_zone_hr,
298
- "snap_after_arsenal_hr": _snap_after_arsenal_hr,
299
- "snap_after_env_hr": _snap_after_env_hr,
300
- "snap_after_platoon_hr": _snap_after_platoon_hr,
301
- "snap_after_traj_hr": _snap_after_traj_hr,
302
- "snap_after_rolling_hr": _snap_after_rolling_hr,
303
- "snap_after_opportunity_hr": _snap_after_opportunity_hr,
304
- "snap_after_drift_hr": _snap_after_drift_hr,
305
- # Opportunity
306
- "expected_pa": opp_adj.get("expected_pa"),
307
- "pa_multiplier": opp_adj.get("pa_multiplier"),
308
- "pitcher_quality_score": opp_adj.get("pitcher_quality_score"),
309
- "opportunity_reason": opp_adj.get("opportunity_reason"),
310
- "lineup_slot_used": opp_adj.get("lineup_slot_used"),
311
- "team_total_used": opp_adj.get("team_total_used"),
312
- "opportunity_mode": opp_adj.get("opportunity_mode"),
313
- # Arsenal drift
314
- "arsenal_hr_adjustment": drift_adj.get("arsenal_hr_adjustment"),
315
- "arsenal_hit_adjustment": drift_adj.get("arsenal_hit_adjustment"),
316
- "arsenal_drift_score": drift_adj.get("arsenal_drift_score"),
317
- "arsenal_reason_tags": drift_adj.get("arsenal_reason_tags"),
318
-
319
- ---
320
- TASK 5 — Full Debug Dashboard
321
-
322
- 5A — Create visualization/debug_page.py
323
-
324
- def render_debug(statcast_df, odds_df, conn, live_games, scores_df) -> None:
325
-
326
- The function renders a full debug page with these sections (use st.header + st.subheader):
327
-
328
- Section 1 — Filters (sidebar or top-of-page)
329
- - Game selector (multiselect from live/scheduled games)
330
- - Player filter (text input)
331
- - Team filter (multiselect)
332
- - Edge threshold (slider 0–20%)
333
-
334
- Section 2 — Model Snapshot Table
335
- - Call build_upcoming_hitter_recommendations() for each selected game
336
- - Display: Player, Game, Slot, hit_prob, hr_prob, tb2p_prob, fair_hr_odds, book_hr_odds, hr_edge, pa_multiplier, pitcher_quality_score
337
- - Apply edge threshold filter
338
-
339
- Section 3 — Adjustment Ladder (per batter, expandable)
340
- - Read exact checkpoint fields from output row (all are exact values logged in-place by the simulator):
341
- Layer | Cumulative HR prob field
342
- ─────────────────────────────────────────────
343
- Baseline | snap_baseline_hr
344
- After Zone | snap_after_zone_hr
345
- After Arsenal | snap_after_arsenal_hr
346
- After Env | snap_after_env_hr
347
- After Platoon | snap_after_platoon_hr
348
- After Trajectory | snap_after_traj_hr
349
- After Rolling | snap_after_rolling_hr
350
- After Opportunity | snap_after_opportunity_hr
351
- After Drift | snap_after_drift_hr
352
- Final (simulated) | hr_prob
353
- - Derive Delta column = current - previous row
354
- - Show as table: Layer | Delta | Cumulative
355
- - Use st.dataframe inside st.expander(batter_name)
356
- - Values are exact (no approximation) — each checkpoint logged immediately after its block in the simulator
357
-
358
- Section 4 — Full Feature Snapshot
359
- - Two columns: batter_features dict + pitcher_row dict
360
- - Use st.json() inside expanders
361
-
362
- Section 5 — Signal Attribution
363
- - rolling_adjustment_reason_tags (pipe-split to rows)
364
- - arsenal_reason_tags
365
- - reason_tags (pitcher live state)
366
- - Show as a flat tag-cloud table
367
-
368
- Section 6 — Admin Tools (moved from debug expander)
369
- - Grade outcomes button → grade_final_game_outcomes_from_scores(scores_df)
370
- - Build prop outcome rows button
371
- - Fill realized outcomes button
372
- - Simulator raw rows table (existing code from lines 3156–3236)
373
- - Phase 6 live-state debug table (existing code from lines 3330–3514)
374
- - Audit metrics (existing code from lines 3516–3682)
375
-
376
- Section 7 — Export
377
- - st.download_button for CSV: sim_df.to_csv(index=False).encode()
378
- - st.download_button for JSON: json.dumps(sim_rows, default=str).encode()
379
-
380
- Section 8 — Audit Metadata (placeholder display)
381
- st.json({
382
- "model_version": "Batch 13",
383
- "feature_version": "rolling_form+opportunity+drift",
384
- "odds_snapshot_id": None,
385
- "data_timestamp": str(pd.Timestamp.now()),
386
- })
387
-
388
- Section 9 — CLV / ERE (existing tables from lines 3617–3661 moved here)
389
-
390
- 5B — Remove debug expander from app.py
391
-
392
- Delete lines 2657–3682 (the entire with st.expander("Debug: raw schedule, scores"): block).
393
-
394
- 5C — Add Debug to navigation in app.py
395
-
396
- In main() at line 3964:
397
- options=[
398
- "Dashboard", "Props", "Matchups",
399
- "Betting", "Bet Tracker", "Algorithm Breakdown", "Debug"
400
- ]
401
-
402
- Add import at top of app.py:
403
- from visualization.debug_page import render_debug
404
-
405
- Add handler in page dispatch:
406
- elif page == "Debug":
407
- render_debug(
408
- statcast_df=load_statcast_recent(),
409
- odds_df=odds_df,
410
- conn=conn,
411
- live_games=live_games,
412
- scores_df=scores_df,
413
- )
414
-
415
- Note: live_games, scores_df, and odds_df are already computed in main() via the shared cached loaders — verify scope or refactor as needed.
416
-
417
- ---
418
- Integration Order (Final)
419
-
420
- batter_baseline (compute_batter_baseline)
421
- ↓ [snapshot baseline_hit/hr/tb2p_prob]
422
- ↓ blended pitch outcome (additive)
423
- ↓ zone matchup (additive)
424
- ↓ family zone matchup (additive)
425
- ↓ arsenal matchup (additive)
426
- ↓ pulled contact (hr only, additive)
427
- ↓ environment (additive)
428
- ↓ platoon/handedness (additive)
429
- ↓ trajectory (additive)
430
- ↓ rolling form (additive) ← Batch 12E
431
- ↓ opportunity (MULTIPLICATIVE × pa_multiplier) ← NEW Batch 13
432
- ↓ arsenal drift (additive) ← NEW Batch 13
433
- ↓ simulate_upcoming_hitter()
434
-
435
- ---
436
- Hard Constraints
437
-
438
- - DO NOT modify engine/live_game_engine.py or simulation/pitch_simulator.py
439
- - All new adjustments must be None-safe with try/except fallbacks
440
- - Opportunity is MULTIPLICATIVE only
441
- - Rolling + Drift are ADDITIVE only
442
- - Drift max effect: ±0.003 HR, ±0.0025 hit (drift_score 0.5 × 0.006/0.005)
443
- - Opportunity max effect: pa_multiplier range [0.85, 1.15]
444
- - estimate_plate_appearance_probability() in opportunity_model.py remains UNCHANGED (used by recommendation_engine.py)
445
-
446
- ---
447
- Verification
448
-
449
- 1. Opportunity: Run simulator with known pitcher (high SwStr) → pa_multiplier < 1.0; with walk-happy pitcher → > 1.0. Check output fields present in sim row.
450
- 2. Drift anti-double-count: Force a pitcher row with large EV spike AND set rolling_reason_tags = "pitcher_ev_allowed_spiking" → drift EV contribution halved.
451
- 3. Debug tab: Navigate to Debug page → loads without crash, all 9 sections render, CSV/JSON download works.
452
- 4. Ladder accuracy: Verify snap_after_drift_hr differs from hr_prob only by the simulation randomness adjustment (expected small delta). Verify snap_baseline_hr
453
- matches compute_batter_baseline output for that player.
454
- 5. No crashes on None inputs: Pass lineup_slot=None, team_total=None, pitcher_row={} → returns pa_multiplier=1.0.
455
- 6. Live engine isolation: Confirm engine/live_game_engine.py and simulation/pitch_simulator.py have zero imports of new modules.
456
- ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
457
-
458
- Claude has written up a plan and is ready to execute. Would you like to proceed?
459
-
460
- ❯ 1. Yes, clear context (56% used) and auto-accept edits
461
- 2. Yes, auto-accept edits
462
- 3. Yes, manually approve edits
463
- 4. Type here to tell Claude what to change
 
1
+ Small Follow-Up Update — Feedback Tab + Batch 13 Debug/Traceability Refinements
2
+
3
+ Context
4
+
5
+ Batch 13 is already in progress / just completed:
6
+ - Opportunity Model
7
+ - Arsenal Drift Layer
8
+ - Full Debug Dashboard
9
+
10
+ This follow-up is intentionally small and surgical. It does TWO things:
11
+
12
+ 1. Add a simple Feedback tab backed by CockroachDB
13
+ 2. Add the remaining debug/traceability refinements we identified for Batch 13
14
+
15
+ Do NOT change live-engine logic.
16
+ Do NOT refactor unrelated systems.
17
+ Keep this focused and minimal.
18
+
19
+ ------------------------------------------------------------
20
+ PART 1 — Feedback Tab (CockroachDB-backed)
21
+ ------------------------------------------------------------
22
+
23
+ Goal
24
+
25
+ Add a very simple Feedback tab for early external users.
26
+
27
+ UI requirements:
28
+ - text box
29
+ - submit button
30
+ - display all submitted feedback below
31
+ - all submissions stored together in CockroachDB
32
+
33
+ Storage requirements:
34
+ - create a new table for feedback
35
+ - table can be created lazily on first submission OR created up front in schema init — choose whichever is simplest and most reliable
36
+ - CockroachDB only, no DuckDB/local files
37
+
38
+ Files to modify:
39
+ - database/db.py
40
+ - visualization/feedback_page.py (new)
41
+ - app.py
42
+
43
+ ------------------------------------------------------------
44
+ 1A — database/db.py
45
+ ------------------------------------------------------------
46
+
47
+ Add a new table:
48
+
49
+ feedback_submissions
50
+
51
+ Recommended schema:
52
+
53
+ CREATE TABLE IF NOT EXISTS feedback_submissions (
54
+ created_at TEXT,
55
+ message TEXT
56
+ )
57
+
58
+ If you want to add an id column and it is easy/safe in CockroachDB, that is fine, but keep it simple.
59
+ Do NOT overengineer this.
60
+
61
+ Add helper functions:
62
+
63
+ ensure_feedback_submissions_table(conn) -> None
64
+
65
+ insert_feedback_submission(conn, message: str) -> None
66
+
67
+ read_feedback_submissions(conn) -> pd.DataFrame
68
+
69
+ Behavior:
70
+ - insert_feedback_submission() should call ensure_feedback_submissions_table() first
71
+ - read_feedback_submissions() should return rows ordered newest first
72
+
73
+ ------------------------------------------------------------
74
+ 1B — visualization/feedback_page.py
75
+ ------------------------------------------------------------
76
+
77
+ Create new file:
78
+ visualization/feedback_page.py
79
+
80
+ Function:
81
+
82
+ render_feedback(conn) -> None
83
+
84
+ UI:
85
+
86
+ - st.header("Feedback")
87
+ - st.text_area(...) for feedback text
88
+ - st.button("Submit")
89
+
90
+ On submit:
91
+ - trim whitespace
92
+ - if empty, show warning
93
+ - otherwise insert into feedback_submissions table
94
+ - show success message
95
+
96
+ Below the form:
97
+ - load all submissions from DB
98
+ - display newest first
99
+ - simple display is fine:
100
+ - created_at in bold
101
+ - message beneath
102
+ - divider between entries
103
+
104
+ Keep it clean and minimal.
105
+ No sentiment analysis, no categories, no editing/deleting.
106
+
107
+ ------------------------------------------------------------
108
+ 1C — app.py
109
+ ------------------------------------------------------------
110
+
111
+ Add import:
112
+ from visualization.feedback_page import render_feedback
113
+
114
+ Add Feedback to navigation options.
115
+
116
+ Route:
117
+ elif page == "Feedback":
118
+ render_feedback(conn)
119
+
120
+ Place it wherever makes sense in nav, but keep it visible.
121
+
122
+ ------------------------------------------------------------
123
+ PART 2 — Batch 13 Debug/Traceability Refinements
124
+ ------------------------------------------------------------
125
+
126
+ These are small follow-up improvements to the just-accepted Batch 13 work.
127
+
128
+ Files to modify:
129
+ - models/live_fair_simulator_v3.py
130
+ - models/arsenal_drift_model.py
131
+ - visualization/debug_page.py
132
+
133
+ ------------------------------------------------------------
134
+ 2A — Add missing exact debug checkpoints
135
+ ------------------------------------------------------------
136
+
137
+ In models/live_fair_simulator_v3.py, add exact checkpoint snapshots for the layers that were still missing from the HR debug ladder:
138
+
139
+ Add:
140
+ - snap_after_family_zone_hr
141
+ - snap_after_pulled_contact_hr
142
+
143
+ Also add equivalent checkpoints for hit/tb2p where relevant.
144
+
145
+ Important:
146
+ - Use exact in-place snapshots immediately after each layer writes back to batter_baseline
147
+ - Do NOT reconstruct later
148
+
149
+ Updated ladder order should reflect all real HR-affecting layers:
150
+
151
+ Baseline
152
+ After Zone
153
+ After Family Zone
154
+ After Arsenal
155
+ After Pulled Contact
156
+ After Env
157
+ After Platoon
158
+ After Trajectory
159
+ After Rolling
160
+ After Opportunity
161
+ After Drift
162
+ Final (simulated hr_prob)
163
+
164
+ ------------------------------------------------------------
165
+ 2B — Log hit and tb2p checkpoint ladders too
166
+ ------------------------------------------------------------
167
+
168
+ Even if the Debug UI only shows HR ladder by default, log the exact checkpoint fields for:
169
+ - HR
170
+ - hit
171
+ - tb2p
172
+
173
+ This is for future audit/admin use.
174
+
175
+ At minimum, ensure output row includes exact checkpoint fields for all three.
176
+
177
+ ------------------------------------------------------------
178
+ 2C — Fix / clarify pitcher drift applied scale
179
+ ------------------------------------------------------------
180
+
181
+ In models/arsenal_drift_model.py, explicitly prevent accidental double sample dampening.
182
+
183
+ Current concern:
184
+ If pitcher_rolling_confidence already includes sample dampening, multiplying again by _sample_scale(n5) reintroduces double-dampening.
185
+
186
+ Requirement:
187
+ - verify what pitcher_rolling_confidence actually represents
188
+ - make drift scaling correct and explicit
189
+
190
+ Valid outcomes:
191
+ 1. If pitcher_rolling_confidence is match-quality only:
192
+ scale = _sample_scale(n5) * confidence
193
+ 2. If pitcher_rolling_confidence already includes sample dampening:
194
+ scale = confidence
195
+
196
+ Whichever is true, enforce it clearly in code/comments.
197
+
198
+ Also add this field to drift output:
199
+ - arsenal_drift_applied_scale
200
+
201
+ This must be surfaced in simulator output for traceability.
202
+
203
+ ------------------------------------------------------------
204
+ 2D — Keep live odds debug panel intentionally
205
+ ------------------------------------------------------------
206
+
207
+ If render_live_prop_odds_debug_panel(live_games) remains on Dashboard, keep it intentionally and make sure it is not orphaned by the debug refactor.
208
+
209
+ Do NOT accidentally remove it unless clearly replacing it with an equivalent section in Debug page.
210
+
211
+ ------------------------------------------------------------
212
+ 2E — Update Debug page ladder
213
+ ------------------------------------------------------------
214
+
215
+ In visualization/debug_page.py:
216
+ - update the Adjustment Ladder section to use the fuller exact checkpoint chain
217
+ - include Family Zone and Pulled Contact in the ladder
218
+ - continue using exact logged fields only
219
+ - no approximation / no reconstruction
220
+
221
+ If feasible without clutter, add a simple toggle