diff --git a/apps/api/src/spin2note_api/clickhouse/client.py b/apps/api/src/spin2note_api/clickhouse/client.py index c63d091..c690599 100644 --- a/apps/api/src/spin2note_api/clickhouse/client.py +++ b/apps/api/src/spin2note_api/clickhouse/client.py @@ -24,7 +24,8 @@ ], "hand_players": [ "hand_id", "user_id", "tournament_format", "effective_stack_bb", "seat", "is_hero", - "villain_hash", "position", "starting_stack", "hole_cards", "won", "result", "parsed_at", + "villain_hash", "position", "starting_stack", "hole_cards", "won", "result", "chip_ev", + "parsed_at", ], "actions": [ "hand_id", "user_id", "tournament_format", "effective_stack_bb", "street", "seat", diff --git a/apps/api/src/spin2note_api/clickhouse/queries.py b/apps/api/src/spin2note_api/clickhouse/queries.py index e514b55..55f062d 100644 --- a/apps/api/src/spin2note_api/clickhouse/queries.py +++ b/apps/api/src/spin2note_api/clickhouse/queries.py @@ -112,6 +112,7 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[ toUInt16(round(effective_stack_bb / 10)) AS bb, count() AS hands, sum(result) AS total_result, + sum(chip_ev) AS total_ev, countIf(result > 0) / count() AS winrate FROM hand_players WHERE user_id = {{u:UUID}} AND is_hero = 1{f_hands} @@ -124,11 +125,38 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[ "effective_stack_bb": int(r[0]), "hands": int(r[1]), "result": round(float(r[2]), 2), - "winrate": round(float(r[3]), 4), + "result_ev": round(float(r[3]), 2), + "winrate": round(float(r[4]), 4), } for r in by_stack.result_rows ] + # Same aggregation grouped by hero position (UTG/HJ/CO/BTN/SB/BB); ordered client-side. + by_position = await client.query( + f""" + SELECT + position, + count() AS hands, + sum(result) AS total_result, + sum(chip_ev) AS total_ev, + countIf(result > 0) / count() AS winrate + FROM hand_players + WHERE user_id = {{u:UUID}} AND is_hero = 1{f_hands} + GROUP BY position + """, + parameters=params, + ) + positions = [ + { + "position": str(r[0]), + "hands": int(r[1]), + "result": round(float(r[2]), 2), + "result_ev": round(float(r[3]), 2), + "winrate": round(float(r[4]), 4), + } + for r in by_position.result_rows + ] + # Cumulative chips P&L over hero hands (time-ordered). Respects the format filter. chips_series = await client.query( f""" @@ -160,6 +188,7 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[ "total_tournaments": total_tournaments, "avg_multiplier": avg_multiplier, "by_stack": stacks, + "by_position": positions, "chips_timeline": chips_timeline, "dollars_timeline": dollars_timeline, } diff --git a/apps/api/src/spin2note_api/domain/models.py b/apps/api/src/spin2note_api/domain/models.py index d20d717..3a942e0 100644 --- a/apps/api/src/spin2note_api/domain/models.py +++ b/apps/api/src/spin2note_api/domain/models.py @@ -47,6 +47,7 @@ class HandPlayer(BaseModel): hole_cards: str = "" won: float = 0.0 result: float = 0.0 + chip_ev: float = 0.0 # all-in-adjusted result; == result unless a 2-way all-in reached showdown parsed_at: datetime = Field(default_factory=_now) diff --git a/apps/api/src/spin2note_api/http/stats.py b/apps/api/src/spin2note_api/http/stats.py index 4095b76..af269ae 100644 --- a/apps/api/src/spin2note_api/http/stats.py +++ b/apps/api/src/spin2note_api/http/stats.py @@ -19,7 +19,16 @@ class StackBucket(BaseModel): effective_stack_bb: int hands: int - result: float + result: float # total chips + result_ev: float # total chipEV (all-in adjusted) + winrate: float + + +class PositionBucket(BaseModel): + position: str + hands: int + result: float # total chips + result_ev: float # total chipEV (all-in adjusted) winrate: float @@ -34,6 +43,7 @@ class Overview(BaseModel): total_tournaments: int avg_multiplier: float by_stack: list[StackBucket] + by_position: list[PositionBucket] chips_timeline: list[TimelinePoint] dollars_timeline: list[TimelinePoint] diff --git a/apps/api/src/spin2note_api/parser/mapping.py b/apps/api/src/spin2note_api/parser/mapping.py index baa1701..efbe59a 100644 --- a/apps/api/src/spin2note_api/parser/mapping.py +++ b/apps/api/src/spin2note_api/parser/mapping.py @@ -53,6 +53,7 @@ def build_hand(parsed: dict[str, Any], user_id: UUID) -> Hand: hole_cards=p["hole_cards"], won=p["won"], result=p["result"], + chip_ev=p["chip_ev"], ) for p in parsed["players"] ] @@ -123,7 +124,7 @@ def build_chunk_rows( player_rows.append(( hid, user_id, fmt, eff, p["seat"], int(p["is_hero"]), p["villain_hash"], p["position"], p["starting_stack"], p["hole_cards"], p["won"], p["result"], - parsed_at, + p["chip_ev"], parsed_at, )) for a in h["actions"]: action_rows.append(( diff --git a/apps/api/tests/test_api.py b/apps/api/tests/test_api.py index 7318fc4..fc535bb 100644 --- a/apps/api/tests/test_api.py +++ b/apps/api/tests/test_api.py @@ -30,7 +30,14 @@ async def fake_overview(_c: Any, _u: Any, _f: Any) -> dict[str, Any]: "total_hands": 10, "total_tournaments": 2, "avg_multiplier": 2.5, - "by_stack": [{"effective_stack_bb": 15, "hands": 10, "result": 120.0, "winrate": 0.6}], + "by_stack": [ + {"effective_stack_bb": 15, "hands": 10, "result": 120.0, + "result_ev": 90.0, "winrate": 0.6} + ], + "by_position": [ + {"position": "BTN", "hands": 6, "result": 80.0, + "result_ev": 70.0, "winrate": 0.5} + ], "chips_timeline": [{"idx": 1, "at": "2026-01-07T22:54:43", "cumulative": 120.0}], "dollars_timeline": [{"idx": 1, "at": "2026-01-07T22:54:43", "cumulative": -0.25}], } @@ -59,6 +66,9 @@ def test_overview_requires_shape(client: TestClient) -> None: body = r.json() assert body["total_hands"] == 10 assert body["by_stack"][0]["winrate"] == 0.6 + assert body["by_stack"][0]["result_ev"] == 90.0 + assert body["by_position"][0]["position"] == "BTN" + assert body["by_position"][0]["result_ev"] == 70.0 def test_overview_rejects_bad_format(client: TestClient) -> None: diff --git a/apps/api/tests/test_parser.py b/apps/api/tests/test_parser.py index 5d675fc..da3cfcd 100644 --- a/apps/api/tests/test_parser.py +++ b/apps/api/tests/test_parser.py @@ -132,3 +132,26 @@ def test_build_tournament_rows_matches_table_columns() -> None: # Tuple arity is the contract with TABLE_COLUMNS; hero_prize sits before parsed_at. assert len(rows[0]) == len(TABLE_COLUMNS["tournaments"]) assert rows[0][TABLE_COLUMNS["tournaments"].index("hero_prize")] == 0.0 + + +def test_chip_ev_present_and_adjusts_allin_showdown() -> None: + # The 3-max sample is a preflop all-in that reaches showdown; chipEV must differ from the + # actual result for the hero (who lost the pot but had equity), and stay within the pot. + h = build_hands(parse(_read("3max/sample.txt")), USER)[0] + hero = next(p for p in h.players if p.is_hero) + assert hero.result == -300.0 + assert hero.chip_ev > hero.result + assert hero.chip_ev < 300.0 + + +def test_build_chunk_rows_player_arity_matches_table_columns() -> None: + from datetime import datetime + + from spin2note_api.clickhouse.client import TABLE_COLUMNS + from spin2note_api.parser import build_chunk_rows + + rows = build_chunk_rows(parse(_read("3max/sample.txt")), USER, datetime(2026, 1, 1)) + cols = TABLE_COLUMNS["hand_players"] + assert len(rows["hand_players"][0]) == len(cols) + # chip_ev column carries a float (the all-in-adjusted result). + assert isinstance(rows["hand_players"][0][cols.index("chip_ev")], float) diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index 4672b40..f82c658 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -2,20 +2,55 @@ import * as React from "react"; -import { ResultByStack } from "@/components/charts/result-by-stack"; import { CumulativeResult } from "@/components/charts/cumulative-result"; +import { MetricByCategory, type CategoryRow } from "@/components/charts/metric-by-category"; import { AppShell } from "@/components/app-shell"; import { Uploader } from "@/components/uploader"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Table, TBody, TD, TH, THead, TR } from "@/components/ui/table"; -import { getOverview, getRecentHands, type Overview, type RecentHand } from "@/lib/api"; +import { + getOverview, + getRecentHands, + type Overview, + type PositionBucket, + type RecentHand, + type StackBucket, +} from "@/lib/api"; import { useAuth } from "@/lib/auth"; import { formatChips, formatUsd } from "@/lib/utils"; type Format = "3max" | "6max" | undefined; +// Canonical poker order (BTN shown for "BU"); positions absent in 3-max simply don't appear. +const POSITION_ORDER = ["UTG", "HJ", "CO", "BTN", "SB", "BB"]; + +function toRow(label: string, b: { hands: number; result: number; result_ev: number; winrate: number }): CategoryRow { + const per = (v: number) => (b.hands > 0 ? (v / b.hands) * 100 : 0); + return { + label, + perHundredChips: per(b.result), + perHundredEv: per(b.result_ev), + totalChips: b.result, + totalEv: b.result_ev, + hands: b.hands, + winrate: b.winrate, + }; +} + +function positionRows(by: PositionBucket[]): CategoryRow[] { + const idx = (p: string) => { + const i = POSITION_ORDER.indexOf(p); + return i === -1 ? POSITION_ORDER.length : i; + }; + return [...by].sort((a, b) => idx(a.position) - idx(b.position)).map((b) => toRow(b.position, b)); +} + +function stackRows(by: StackBucket[]): CategoryRow[] { + return by.map((b) => toRow(`${b.effective_stack_bb}bb`, b)); +} + function Stat({ title, value }: { title: string; value: string }) { return ( @@ -86,11 +121,26 @@ function Dashboard() { - Net result by effective stack (BB) + By position — chips/100 vs chipEV/100 +

Where you earn most/least by seat (BU = BTN). chipEV strips all-in variance.

+
+ + {overview && overview.by_position.length > 0 ? ( + + ) : ( +

No hands yet — upload a hand history.

+ )} +
+
+ + + + By effective stack — chips/100 vs chipEV/100 +

Where you earn most/least by tournament stage (stack depth in BB).

{overview && overview.by_stack.length > 0 ? ( - + ) : (

No hands yet — upload a hand history.

)} diff --git a/apps/web/src/components/charts/metric-by-category.tsx b/apps/web/src/components/charts/metric-by-category.tsx new file mode 100644 index 0000000..67c8b70 --- /dev/null +++ b/apps/web/src/components/charts/metric-by-category.tsx @@ -0,0 +1,62 @@ +"use client"; + +import { + Bar, + BarChart, + CartesianGrid, + Legend, + ReferenceLine, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; + +import { formatChips, formatPer100 } from "@/lib/utils"; + +export type CategoryRow = { + label: string; + perHundredChips: number; + perHundredEv: number; + totalChips: number; + totalEv: number; + hands: number; + winrate: number; +}; + +const CHIPS = "hsl(152 70% 45%)"; +const EV = "hsl(210 90% 60%)"; + +function CategoryTooltip({ active, payload }: { active?: boolean; payload?: { payload: CategoryRow }[] }) { + if (!active || !payload?.length) return null; + const r = payload[0].payload; + return ( +
+
{r.label}
+
chips/100: {formatPer100(r.perHundredChips)}
+
chipEV/100: {formatPer100(r.perHundredEv)}
+
+ total {formatChips(r.totalChips)} · EV {formatChips(r.totalEv)} +
+
{r.hands.toLocaleString("en-US")} hands · {(r.winrate * 100).toFixed(1)}% won
+
+ ); +} + +/** Grouped bars per category (position or stack): chips/100 vs chipEV/100. */ +export function MetricByCategory({ data }: { data: CategoryRow[] }) { + return ( + + + + + + + } /> + + + + + + ); +} diff --git a/apps/web/src/components/charts/result-by-stack.tsx b/apps/web/src/components/charts/result-by-stack.tsx deleted file mode 100644 index 6fb6809..0000000 --- a/apps/web/src/components/charts/result-by-stack.tsx +++ /dev/null @@ -1,40 +0,0 @@ -"use client"; - -import { - Bar, - BarChart, - CartesianGrid, - Cell, - ResponsiveContainer, - Tooltip, - XAxis, - YAxis, -} from "recharts"; - -import type { StackBucket } from "@/lib/api"; - -export function ResultByStack({ data }: { data: StackBucket[] }) { - const rows = data.map((d) => ({ bb: `${d.effective_stack_bb}bb`, result: d.result })); - return ( - - - - - - - - {rows.map((r, i) => ( - = 0 ? "hsl(152 70% 45%)" : "hsl(0 72% 51%)"} /> - ))} - - - - ); -} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 70cc94c..bc2180b 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -3,6 +3,7 @@ import type { components } from "./api/schema"; // Types come straight from the backend OpenAPI spec (regenerate via `npm run generate-client`). export type Overview = components["schemas"]["Overview"]; export type StackBucket = components["schemas"]["StackBucket"]; +export type PositionBucket = components["schemas"]["PositionBucket"]; export type TimelinePoint = components["schemas"]["TimelinePoint"]; export type RecentHand = components["schemas"]["RecentHand"]; export type UploadResult = components["schemas"]["UploadResult"]; diff --git a/apps/web/src/lib/api/schema.ts b/apps/web/src/lib/api/schema.ts index 5052757..4480443 100644 --- a/apps/web/src/lib/api/schema.ts +++ b/apps/web/src/lib/api/schema.ts @@ -197,11 +197,26 @@ export interface components { avg_multiplier: number; /** By Stack */ by_stack: components["schemas"]["StackBucket"][]; + /** By Position */ + by_position: components["schemas"]["PositionBucket"][]; /** Chips Timeline */ chips_timeline: components["schemas"]["TimelinePoint"][]; /** Dollars Timeline */ dollars_timeline: components["schemas"]["TimelinePoint"][]; }; + /** PositionBucket */ + PositionBucket: { + /** Position */ + position: string; + /** Hands */ + hands: number; + /** Result */ + result: number; + /** Result Ev */ + result_ev: number; + /** Winrate */ + winrate: number; + }; /** RecentHand */ RecentHand: { /** Source Hand Id */ @@ -227,6 +242,8 @@ export interface components { hands: number; /** Result */ result: number; + /** Result Ev */ + result_ev: number; /** Winrate */ winrate: number; }; diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts index 04c7c30..799605a 100644 --- a/apps/web/src/lib/utils.ts +++ b/apps/web/src/lib/utils.ts @@ -18,3 +18,9 @@ export function formatUsd(value: number): string { }); return `${sign}$${abs}`; } + +/** Chips per 100 hands, rounded — the comparable winrate metric for the per-spot bars. */ +export function formatPer100(value: number): string { + const sign = value > 0 ? "+" : ""; + return `${sign}${Math.round(value).toLocaleString("en-US")}`; +} diff --git a/crates/hh-parser/src/equity.rs b/crates/hh-parser/src/equity.rs new file mode 100644 index 0000000..31bcfd8 --- /dev/null +++ b/crates/hh-parser/src/equity.rs @@ -0,0 +1,281 @@ +//! All-in equity for chipEV: each player's share of the pot if the hand were run out many times +//! from the moment the last chips went in. Flop/turn/river all-ins are enumerated exhaustively; +//! preflop all-ins use seeded Monte-Carlo (deterministic — same hand always yields the same EV). +//! +//! Self-contained: a constant-time 7-card evaluator and a SplitMix64 PRNG, no external crates. + +const PREFLOP_SAMPLES: usize = 20_000; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Card { + rank: u8, // 2..=14 (T=10, J=11, Q=12, K=13, A=14) + suit: u8, // 0..=3 +} + +/// Parse the space-separated "Qd Ts" card format used in `hole_cards` / `board`. +pub fn parse_cards(s: &str) -> Option> { + s.split_whitespace().map(parse_card).collect() +} + +fn parse_card(tok: &str) -> Option { + let b = tok.as_bytes(); + if b.len() < 2 { + return None; + } + let rank = match b[0] { + d @ b'2'..=b'9' => d - b'0', + b'T' | b't' => 10, + b'J' | b'j' => 11, + b'Q' | b'q' => 12, + b'K' | b'k' => 13, + b'A' | b'a' => 14, + _ => return None, + }; + let suit = match b[1] { + b's' | b'S' => 0, + b'h' | b'H' => 1, + b'd' | b'D' => 2, + b'c' | b'C' => 3, + _ => return None, + }; + Some(Card { rank, suit }) +} + +/// Equity (win probability + split share of ties) for each player's 2-card hand, given the board +/// cards already known. Returns a vector parallel to `holes`, summing to ~1.0. +pub fn equity(holes: &[Vec], board_known: &[Card], seed: u64) -> Vec { + let n = holes.len(); + let mut dead: Vec = Vec::new(); + for h in holes { + dead.extend_from_slice(h); + } + dead.extend_from_slice(board_known); + let deck: Vec = (0..52u8) + .map(|i| Card { rank: i % 13 + 2, suit: i / 13 }) + .filter(|c| !dead.contains(c)) + .collect(); + let need = 5 - board_known.len(); + + let mut wins = vec![0.0f64; n]; + let mut trials = 0u64; + let mut tally = |runout: &[Card]| { + let mut best = 0u32; + let mut scores = [0u32; 8]; // up to 8 players (more than any Spin&Gold table) + for (i, h) in holes.iter().enumerate() { + let mut cs: Vec = Vec::with_capacity(7); + cs.extend_from_slice(h); + cs.extend_from_slice(board_known); + cs.extend_from_slice(runout); + let s = eval7(&cs); + scores[i] = s; + if s > best { + best = s; + } + } + let winners = (0..n).filter(|&i| scores[i] == best).count(); + let share = 1.0 / winners as f64; + for i in 0..n { + if scores[i] == best { + wins[i] += share; + } + } + }; + + if need == 0 { + tally(&[]); + trials = 1; + } else if need == 1 { + for &c in &deck { + tally(&[c]); + trials += 1; + } + } else if need == 2 { + for i in 0..deck.len() { + for j in (i + 1)..deck.len() { + tally(&[deck[i], deck[j]]); + trials += 1; + } + } + } else { + // Preflop (need == 5): exhaustive C(48,5) is too slow per hand, so Monte-Carlo. + let mut rng = SplitMix64::new(seed); + let mut idx: Vec = (0..deck.len()).collect(); + for _ in 0..PREFLOP_SAMPLES { + for k in 0..need { + let r = k + (rng.next() as usize) % (idx.len() - k); + idx.swap(k, r); + } + let runout: Vec = (0..need).map(|k| deck[idx[k]]).collect(); + tally(&runout); + trials += 1; + } + } + wins.iter().map(|w| w / trials as f64).collect() +} + +/// Rank a 7-card hand into a comparable score (higher is better). The top bits encode the hand +/// category (8=straight flush … 0=high card); the low bits encode tie-break ranks. +fn eval7(cards: &[Card]) -> u32 { + let mut rank_cnt = [0u8; 15]; + let mut suit_cnt = [0u8; 4]; + let mut suit_rank_mask = [0u16; 4]; + let mut rank_mask: u16 = 0; + for c in cards { + rank_cnt[c.rank as usize] += 1; + suit_cnt[c.suit as usize] += 1; + suit_rank_mask[c.suit as usize] |= 1 << c.rank; + rank_mask |= 1 << c.rank; + } + let mut best = made_score(&rank_cnt, rank_mask); + if let Some(h) = straight_high(rank_mask) { + best = best.max(score(4, &[h, 0, 0, 0, 0])); + } + for s in 0..4 { + if suit_cnt[s] >= 5 { + best = best.max(score(5, &top_ranks(suit_rank_mask[s], 5))); + if let Some(h) = straight_high(suit_rank_mask[s]) { + best = best.max(score(8, &[h, 0, 0, 0, 0])); + } + } + } + best +} + +fn made_score(rank_cnt: &[u8; 15], rank_mask: u16) -> u32 { + let (mut quads, mut trips, mut pairs) = (Vec::new(), Vec::new(), Vec::new()); + for r in (2u8..=14).rev() { + match rank_cnt[r as usize] { + 4 => quads.push(r), + 3 => trips.push(r), + 2 => pairs.push(r), + _ => {} + } + } + if let Some(&q) = quads.first() { + let k = top_excluding(rank_mask, &[q], 1); + return score(7, &[q, k[0], 0, 0, 0]); + } + if let Some(&t) = trips.first() { + let mut pair = if trips.len() >= 2 { trips[1] } else { 0 }; + if let Some(&p) = pairs.first() { + if p > pair { + pair = p; + } + } + if pair > 0 { + return score(6, &[t, pair, 0, 0, 0]); + } + let k = top_excluding(rank_mask, &[t], 2); + return score(3, &[t, k[0], k[1], 0, 0]); + } + if pairs.len() >= 2 { + let (p1, p2) = (pairs[0], pairs[1]); + let k = top_excluding(rank_mask, &[p1, p2], 1); + return score(2, &[p1, p2, k[0], 0, 0]); + } + if let Some(&p) = pairs.first() { + let k = top_excluding(rank_mask, &[p], 3); + return score(1, &[p, k[0], k[1], k[2], 0]); + } + score(0, &top_ranks(rank_mask, 5)) +} + +/// Highest card of the best 5-straight in `mask` (ranks at bits 2..=14), or None. Handles the +/// wheel (A-2-3-4-5) by treating the ace as a low card. +fn straight_high(mask: u16) -> Option { + let m = if mask & (1 << 14) != 0 { mask | (1 << 1) } else { mask }; + for high in (5u8..=14).rev() { + if (high - 4..=high).all(|r| m & (1 << r) != 0) { + return Some(high); + } + } + None +} + +fn top_ranks(mask: u16, n: usize) -> [u8; 5] { + let mut out = [0u8; 5]; + let mut i = 0; + for r in (2u8..=14).rev() { + if i >= n { + break; + } + if mask & (1 << r) != 0 { + out[i] = r; + i += 1; + } + } + out +} + +fn top_excluding(mask: u16, excl: &[u8], n: usize) -> [u8; 5] { + let mut out = [0u8; 5]; + let mut i = 0; + for r in (2u8..=14).rev() { + if i >= n { + break; + } + if mask & (1 << r) != 0 && !excl.contains(&r) { + out[i] = r; + i += 1; + } + } + out +} + +fn score(cat: u32, r: &[u8; 5]) -> u32 { + (cat << 20) + | ((r[0] as u32) << 16) + | ((r[1] as u32) << 12) + | ((r[2] as u32) << 8) + | ((r[3] as u32) << 4) + | (r[4] as u32) +} + +struct SplitMix64 { + state: u64, +} + +impl SplitMix64 { + fn new(seed: u64) -> Self { + Self { state: seed } + } + fn next(&mut self) -> u64 { + self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cards(s: &str) -> Vec { + parse_cards(s).unwrap() + } + + #[test] + fn aces_dominate_kings_preflop() { + let eq = equity(&[cards("Ah As"), cards("Kh Ks")], &[], 12345); + assert!((eq[0] - 0.82).abs() < 0.03, "AA equity {} not ~0.82", eq[0]); + assert!((eq[0] + eq[1] - 1.0).abs() < 1e-9); + } + + #[test] + fn made_flush_beats_made_straight_on_river() { + // Player A makes a flush, player B a straight; board fixed (need == 0, deterministic). + let eq = equity(&[cards("Ah 2h"), cards("9s 8s")], &cards("Th Jh 7h 6d 5c"), 0); + assert_eq!(eq[0], 1.0); + assert_eq!(eq[1], 0.0); + } + + #[test] + fn split_pot_is_half_each() { + // Both play the board (royal-ish straight on board) -> tie. + let eq = equity(&[cards("2c 3d"), cards("4c 5d")], &cards("As Ks Qs Js Ts"), 0); + assert_eq!(eq[0], 0.5); + assert_eq!(eq[1], 0.5); + } +} diff --git a/crates/hh-parser/src/lib.rs b/crates/hh-parser/src/lib.rs index 7bbca89..0eeeb32 100644 --- a/crates/hh-parser/src/lib.rs +++ b/crates/hh-parser/src/lib.rs @@ -8,6 +8,7 @@ //! Pure parsing lives in plain functions returning Rust structs (unit-tested without Python); //! the `#[pyfunction]`s are thin converters to Python dicts. +mod equity; mod model; mod parser; mod summary; @@ -102,6 +103,7 @@ fn player_to_py<'py>(py: Python<'py>, p: &Player) -> PyResult d.set_item("won", p.won)?; d.set_item("invested", p.invested)?; d.set_item("result", p.result)?; + d.set_item("chip_ev", p.chip_ev)?; Ok(d) } diff --git a/crates/hh-parser/src/model.rs b/crates/hh-parser/src/model.rs index 00c8842..15b3635 100644 --- a/crates/hh-parser/src/model.rs +++ b/crates/hh-parser/src/model.rs @@ -24,6 +24,7 @@ pub struct Player { pub won: f64, pub invested: f64, pub result: f64, + pub chip_ev: f64, // all-in-adjusted result; == result unless a 2-way all-in reached showdown } #[derive(Debug, Clone)] diff --git a/crates/hh-parser/src/parser.rs b/crates/hh-parser/src/parser.rs index 83ecf43..1cb9246 100644 --- a/crates/hh-parser/src/parser.rs +++ b/crates/hh-parser/src/parser.rs @@ -117,6 +117,7 @@ pub fn parse_hand(block: &str) -> Option { won: 0.0, invested: 0.0, result: 0.0, + chip_ev: 0.0, }); } continue; @@ -248,6 +249,10 @@ pub fn parse_hand(block: &str) -> Option { let hand_id = deterministic_hand_id(&tournament_id, &source_hand_id); + // All-in-adjusted result (chipEV): replace the runout gamble with equity * pot for the + // qualifying 2-player all-in showdown; everything else keeps the actual result. + assign_chip_ev(&mut players, &actions, &board, pot, villain_hash(&hand_id)); + Some(Hand { hand_id, source_hand_id, @@ -268,6 +273,58 @@ pub fn parse_hand(block: &str) -> Option { }) } +/// Set `chip_ev` for every player. Default is the actual `result`; only when exactly two players +/// reach showdown all-in with both hole cards known do we replace it with `equity * pot - invested` +/// (variance removed). Multiway all-ins (side pots) are out of scope for v1 and keep the actual result. +fn assign_chip_ev(players: &mut [Player], actions: &[Action], board: &str, pot: f64, seed: u64) { + use std::collections::HashSet; + for p in players.iter_mut() { + p.chip_ev = p.result; + } + let folded: HashSet = actions.iter().filter(|a| a.kind == "fold").map(|a| a.seat).collect(); + let all_in: HashSet = actions.iter().filter(|a| a.all_in).map(|a| a.seat).collect(); + + let live: Vec = (0..players.len()) + .filter(|&i| !folded.contains(&players[i].seat)) + .collect(); + // Exactly two live players, both all-in, both with known cards. + if live.len() != 2 || !live.iter().all(|&i| all_in.contains(&players[i].seat)) { + return; + } + let mut holes = Vec::with_capacity(2); + for &i in &live { + match crate::equity::parse_cards(&players[i].hole_cards) { + Some(c) if c.len() == 2 => holes.push(c), + _ => return, + } + } + // Board known at the moment the last chips went in (the latest all-in street). + let street_rank = |s: &str| match s { + "flop" => 1, + "turn" => 2, + "river" => 3, + _ => 0, + }; + let lock = actions.iter().filter(|a| a.all_in).map(|a| street_rank(a.street)).max().unwrap_or(0); + let need_board = match lock { + 0 => 0, + 1 => 3, + 2 => 4, + _ => 5, + }; + let board_cards = match crate::equity::parse_cards(board) { + Some(c) => c, + None => return, + }; + if board_cards.len() < need_board { + return; + } + let eq = crate::equity::equity(&holes, &board_cards[..need_board], seed); + for (k, &i) in live.iter().enumerate() { + players[i].chip_ev = eq[k] * pot - players[i].invested; + } +} + fn effective_stack(players: &[Player], big_blind: f64) -> u16 { let hero = players.iter().find(|p| p.is_hero); let max_opp = players @@ -453,6 +510,30 @@ Seat 3: f55138e4 (big blind) showed [3h 4h] and won (600) with three of a kind, assert!(net.abs() < 1e-6); } + #[test] + fn chip_ev_adjusts_allin_showdown() { + let h = parse_hand(ALLIN_SHOWDOWN).expect("hand"); + let hero = h.players.iter().find(|p| p.is_hero).unwrap(); + let winner = h.players.iter().find(|p| p.name == "f55138e4").unwrap(); + + // Hero lost the actual pot (-300) but had real equity, so chipEV pulls it up; the lucky + // winner's chipEV is pulled below their +300. Both stay within the pot bounds. + assert!(hero.chip_ev > hero.result && hero.chip_ev < 300.0); + assert!(winner.chip_ev < winner.result && winner.chip_ev > -300.0); + // chipEV is zero-sum across the table (rake 0), like result. + let net_ev: f64 = h.players.iter().map(|p| p.chip_ev).sum(); + assert!(net_ev.abs() < 1e-6, "chipEV net {net_ev} not ~0"); + } + + #[test] + fn chip_ev_equals_result_without_allin_showdown() { + // No all-in / villain folds: nothing to adjust, chipEV mirrors result exactly. + let h = parse_hand(MULTI_STREET).expect("hand"); + for p in &h.players { + assert_eq!(p.chip_ev, p.result); + } + } + const MULTI_STREET: &str = "\ Poker Hand #SG3478637237: Tournament #256047018, Spin&Gold #7 Hold'em No Limit - Level1(10/20) - 2026/01/07 22:55:52 Table '17028' 3-max Seat #1 is the button diff --git a/migrations/clickhouse/0004_chip_ev.sql b/migrations/clickhouse/0004_chip_ev.sql new file mode 100644 index 0000000..a863907 --- /dev/null +++ b/migrations/clickhouse/0004_chip_ev.sql @@ -0,0 +1,3 @@ +-- All-in-adjusted per-player result (chipEV). Equals `result` for hands without a 2-player all-in +-- showdown; otherwise the runout is replaced by equity*pot. Powers variance-free per-spot stats. +ALTER TABLE hand_players ADD COLUMN IF NOT EXISTS chip_ev Float64 AFTER result;