Replay-Harness, Wurzel-Fix am Equity-Bias, MDF-River-Boden und Stage-0-Blind-Messlatte
Replay-Harness (entscheiden/replay.py, eval7.py, tests/replay_spec.py): rekonstruiert Hero- Entscheidungen aus echten Hand-Histories, misst Fold-to-bet, den Equity-Bias gegen einen unabhaengigen Evaluator und den belegten EV-Verlust (Overfold/Overcall). benchmarks/replay_*.txt frieren Vorher/Nachher ein. Wurzel am Equity-Bias (exploit/bluff_share.rs, street_continuation.rs): der Micro-Pool barrelt ueber GTO-Balance, also bekommt eine UNGELESENE Range (profile None, auch blind gegatet) auf dem ERSTEN Barrel einen Populations-Ueber-Bluff-Prior (with_pop_prior, barrel-bewusst - ein Sustained- Barrel bleibt value-gewichtet). bluff_share bleibt rein. Overfold im Replay 40.6 -> 7.5 bb, Bias -0.221 -> -0.186. MDF-River-Boden (exploit/mdf_floor.rs, engine/decide.rs): ein River-Fold einer verteidigbaren Made-Hand gegen eine Range, die bluffen kann, wird zum Call (MDF/Break-even), ausser jeder lebende Gegner ist ein belegter Under-Bluffer. Laeuft auf dem UNGEGATETEN Spot, Kern-EV unangetastet. Stage 0 - Blind-Messlatte (sim/session.rs, table.rs, benchmark.rs, tests/sim_blind.rs): ein neues blind-Feld haelt den HUD-Read zurueck; zwei Blind-Szenarien (Fisch, Calling Station) beziffern den Sitzungsertrag eines Reads (Fisch +53.8, Station +26.3 bb/100). Die 10 alten Szenarien bleiben Bit fuer Bit gleich; baseline.txt neu mit 12 Szenarien. Kein Rueckschritt auf der Messlatte. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+27
-17
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
label 5f68c71+lokal
|
||||
export coinpoker_cash_2026-11-10
|
||||
hands 161
|
||||
spots 195
|
||||
facing_bet 28
|
||||
faithfulness 0.851
|
||||
faithfulness_bet 0.679
|
||||
foldbet_flop 6 9
|
||||
foldbet_turn 3 3
|
||||
foldbet_river 2 5
|
||||
equity_bias -0.186 n=14
|
||||
overfold_bb 7.5
|
||||
overcall_bb 3.1
|
||||
@@ -0,0 +1,13 @@
|
||||
label 5f68c71+lokal
|
||||
export coinpoker_cash_2026-11-10
|
||||
hands 161
|
||||
spots 195
|
||||
facing_bet 28
|
||||
faithfulness 0.882
|
||||
faithfulness_bet 0.893
|
||||
foldbet_flop 8 7
|
||||
foldbet_turn 3 3
|
||||
foldbet_river 6 1
|
||||
equity_bias -0.221 n=14
|
||||
overfold_bb 40.6
|
||||
overcall_bb 3.1
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unabhaengiger 7-Karten-Evaluator und River/Runout-Equity - der GROUND TRUTH des Replay-Benchmarks.
|
||||
|
||||
Bewusst NICHT die Engine (src/hand): der Benchmark benotet die Engine, also darf der Massstab nicht
|
||||
aus derselben Quelle stammen. Klein, offensichtlich korrekt, mit Selbsttest (`_selftest`).
|
||||
|
||||
from eval7 import equity_vs, best7, karten
|
||||
"""
|
||||
import itertools
|
||||
from collections import Counter
|
||||
|
||||
RANG = {r: i for i, r in enumerate("23456789TJQKA", 2)}
|
||||
FARBEN = "shdc"
|
||||
VOLLDECK = [(r, s) for r in range(2, 15) for s in FARBEN]
|
||||
|
||||
|
||||
def karte(t):
|
||||
"""'As' -> (14, 's'); robust gegen 10/Zehn-Schreibweisen."""
|
||||
t = t.strip()
|
||||
return (RANG[t[0]], t[1])
|
||||
|
||||
|
||||
def karten(s):
|
||||
"""'As Kd' oder Liste -> [(14,'s'),(13,'d')]."""
|
||||
if isinstance(s, (list, tuple)):
|
||||
return [karte(x) for x in s]
|
||||
return [karte(x) for x in s.split()]
|
||||
|
||||
|
||||
def score5(cards):
|
||||
"""Vergleichbarer Wert einer 5-Karten-Hand: (Kategorie, Kicker-Liste). Groesser = besser."""
|
||||
rks = sorted((c[0] for c in cards), reverse=True)
|
||||
suits = [c[1] for c in cards]
|
||||
cnt = Counter(rks)
|
||||
flush = len(set(suits)) == 1
|
||||
dist = sorted(set(rks), reverse=True)
|
||||
sh = None
|
||||
if len(dist) == 5:
|
||||
if dist[0] - dist[4] == 4:
|
||||
sh = dist[0]
|
||||
elif dist == [14, 5, 4, 3, 2]: # Wheel A-2-3-4-5
|
||||
sh = 5
|
||||
# Raenge nach (Anzahl, Rang) ordnen -> Kicker fuer Paare/Drillinge/Full House
|
||||
seen = []
|
||||
for r in sorted(rks, key=lambda r: (cnt[r], r), reverse=True):
|
||||
if r not in seen:
|
||||
seen.append(r)
|
||||
pat = sorted(cnt.values(), reverse=True)
|
||||
if sh and flush:
|
||||
return (8, [sh])
|
||||
if pat == [4, 1]:
|
||||
return (7, seen)
|
||||
if pat == [3, 2]:
|
||||
return (6, seen)
|
||||
if flush:
|
||||
return (5, rks)
|
||||
if sh:
|
||||
return (4, [sh])
|
||||
if pat == [3, 1, 1]:
|
||||
return (3, seen)
|
||||
if pat == [2, 2, 1]:
|
||||
return (2, seen)
|
||||
if pat == [2, 1, 1, 1]:
|
||||
return (1, seen)
|
||||
return (0, rks)
|
||||
|
||||
|
||||
def best7(cards7):
|
||||
"""Beste 5 aus 7 (oder aus 5/6) Karten."""
|
||||
if len(cards7) <= 5:
|
||||
return score5(list(cards7))
|
||||
return max(score5(list(c)) for c in itertools.combinations(cards7, 5))
|
||||
|
||||
|
||||
def equity_vs(hero, board, vils):
|
||||
"""Exakte Equity von `hero` (2 Karten) auf `board` (3-5) gegen bekannte Gegnerhaende `vils`.
|
||||
|
||||
Enumeriert ALLE Runouts (kein Monte Carlo): am River exakt der Showdown, am Flop/Turn der
|
||||
Mittelwert ueber alle Boardvervollstaendigungen. Ties zaehlen anteilig."""
|
||||
hero = karten(hero) if not isinstance(hero[0], tuple) else hero
|
||||
board = karten(board) if board and not isinstance(board[0], tuple) else list(board)
|
||||
vils = [karten(v) if not isinstance(v[0], tuple) else v for v in vils]
|
||||
bekannt = set(hero) | set(board)
|
||||
for v in vils:
|
||||
bekannt |= set(v)
|
||||
deck = [c for c in VOLLDECK if c not in bekannt]
|
||||
miss = 5 - len(board)
|
||||
won = 0.0
|
||||
n = 0
|
||||
for extra in itertools.combinations(deck, miss):
|
||||
full = board + list(extra)
|
||||
hs = best7(hero + full)
|
||||
vstr = [best7(v + full) for v in vils]
|
||||
mx = max(vstr)
|
||||
if hs > mx:
|
||||
won += 1.0
|
||||
elif hs == mx:
|
||||
won += 1.0 / (1 + sum(1 for x in vstr if x == hs))
|
||||
n += 1
|
||||
return won / n if n else 0.0
|
||||
|
||||
|
||||
def _selftest():
|
||||
b = karten("Ts Th 5d Tc 8c")
|
||||
assert best7(b + karten("As 6h")) > best7(b + karten("Ks 4h")) # TTT+A schlaegt TTT+K
|
||||
assert score5(karten("Ah Kh Qh Jh 9h"))[0] == 5 # Flush
|
||||
assert score5(karten("Ah Kd Qh Jh Th"))[0] == 4 # Strasse
|
||||
assert score5(karten("Ah 2d 3h 4h 5h"))[0] == 4 # Wheel
|
||||
assert score5(karten("Ah Ad Ac Ks Kd"))[0] == 6 # Full House
|
||||
assert score5(karten("Ah Ad Ac As Kd"))[0] == 7 # Quads
|
||||
assert equity_vs("Ac Ad", "Kc 7h 2s", ["Kh Qd"]) > 0.78 # AA schlaegt Top Pair KQ klar
|
||||
assert equity_vs("Kc 7s", karten("Qc 2h Kd 6d 8d"), ["Ad Qh"]) == 1.0 # River: top pair K schlaegt QQ
|
||||
assert equity_vs("Ac Ad", "2h 3h 4h 5h 9s", ["6h 7h"]) == 0.0 # River: fertiger Flush schlaegt AA
|
||||
|
||||
|
||||
_selftest()
|
||||
|
||||
if __name__ == "__main__":
|
||||
_selftest()
|
||||
print("eval7 Selbsttest ok")
|
||||
@@ -0,0 +1,335 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay-Benchmark: der EHRLICHE Postflop-Massstab aus echten Hand-Histories.
|
||||
|
||||
Statt bb/100 gegen selbstgeschriebene Bots (die nur messen, ob wir die EIGENEN Fische schlagen)
|
||||
treibt dieser Benchmark die ECHTE, AKTUELLE Engine ueber jede Hero-Entscheidung einer realen Session
|
||||
und benotet sie gegen einen UNABHAENGIGEN Evaluator (`eval7`) auf den tatsaechlich gezeigten
|
||||
Gegnerkarten. Jeder Hero-Spot wird aus der Hand-History als Wire-Anfrage rekonstruiert (board, pot,
|
||||
toCall, Stacks, history, Profile) und neu entschieden - so misst der Benchmark FIXES, nicht nur die
|
||||
alte Session.
|
||||
|
||||
Vier Masse:
|
||||
* TREUE: reproduziert die Re-Decision die geloggte Linie? (Rekonstruktion korrekt?)
|
||||
* EV-VERLUST: wo der Gegner zeigt - foldet die Engine +EV-Calls weg / callt sie -EV-Spots? (bb)
|
||||
* EQUITY-BIAS: Engine-Equity minus WAHRE Equity (negativ = unterschaetzt -> Overfold-Wurzel)
|
||||
* FOLD/MDF: Fold-gegen-Bet je Street gegen die Minimum-Defense-Frequency
|
||||
|
||||
COINPOKER_EXPORT=/pfad/zur/session.md python3 entscheiden/replay.py
|
||||
COINPOKER_KERN=.../target/release/rechner.exe # Engine-Binary (Default: target/release/rechner)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import Counter
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import decide
|
||||
from eval7 import equity_vs, karten
|
||||
|
||||
HERO = "mmintel"
|
||||
RANG = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", "8": "EIGHT",
|
||||
"7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"}
|
||||
FARBE = {"s": "SPADES", "h": "HEARTS", "d": "DIAMONDS", "c": "CLUBS"}
|
||||
STREETS = ["PREFLOP", "FLOP", "TURN", "RIVER"]
|
||||
|
||||
|
||||
def _wire_card(t):
|
||||
return {"rank": RANG[t[0]], "suit": FARBE[t[1]]}
|
||||
|
||||
|
||||
def _wire_cards(txt):
|
||||
return [_wire_card(x) for x in txt.split()]
|
||||
|
||||
|
||||
def _board_dict(board_cards):
|
||||
"""5-Karten-Board (Textliste) -> Wire-Board-Dict bis zur erreichten Street."""
|
||||
d = {}
|
||||
if len(board_cards) >= 3:
|
||||
d["FLOP"] = [_wire_card(c) for c in board_cards[:3]]
|
||||
if len(board_cards) >= 4:
|
||||
d["TURN"] = [_wire_card(board_cards[3])]
|
||||
if len(board_cards) >= 5:
|
||||
d["RIVER"] = [_wire_card(board_cards[4])]
|
||||
return d
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- HH-Parser
|
||||
ACT_RE = re.compile(r'^(\S+): (posts small blind|posts big blind|posts the ante|folds|checks|'
|
||||
r'bets|calls|raises)(?: \$?([0-9.]+))?(?: to \$?([0-9.]+))?', re.M)
|
||||
|
||||
|
||||
def parse_hand(block):
|
||||
"""MD-Handblock -> dict mit allem fuer die Rekonstruktion, oder None wenn unbrauchbar."""
|
||||
hid = block.split(" ", 1)[0].lstrip("#")
|
||||
mhole = re.search(r'Hero Hole Cards:\*\* `([^`]+)`', block)
|
||||
mhh = re.search(r'```text\n(.*?)```', block, re.S)
|
||||
if not mhole or not mhh:
|
||||
return None
|
||||
hero_cards = mhole.group(1).split()
|
||||
hh = mhh.group(1)
|
||||
|
||||
# Engine-Entscheidungen (Street, board, pot, toCall, action) in Dokumentreihenfolge
|
||||
dec_re = re.compile(r'`(PREFLOP|FLOP|TURN|RIVER)` \| board=`([^`]*)` \| '
|
||||
r'pot=\$([0-9.]+) toCall=\$([0-9.]+) \| \*\*([A-Z]+)\*\* \| '
|
||||
r'eq=([0-9.]+|None) \| (.*)')
|
||||
decisions = [{"street": m.group(1), "board": m.group(2).split(), "pot": float(m.group(3)),
|
||||
"to_call": float(m.group(4)), "action": m.group(5),
|
||||
"eq": None if m.group(6) == "None" else float(m.group(6)), "reason": m.group(7)}
|
||||
for m in dec_re.finditer(block)]
|
||||
if not decisions:
|
||||
return None
|
||||
|
||||
# VPIP/Hands je Name aus der Players-Zeile
|
||||
prof = {}
|
||||
for mm in re.finditer(r'S\d+ (\S+) \(\$[0-9.]+, VPIP (\d+)%/(\d+)h\)', block):
|
||||
prof[mm.group(1)] = {"vpip": int(mm.group(2)) / 100.0, "hands": int(mm.group(3))}
|
||||
|
||||
# Sitze, Stacks, Button, Blinds, Showdown-Karten aus der HH
|
||||
seats = {} # name -> seat
|
||||
stacks = {} # name -> start stack
|
||||
for mm in re.finditer(r'^Seat (\d+): (\S+) \(\$([0-9.]+) in chips\)', hh, re.M):
|
||||
seats[mm.group(2)] = int(mm.group(1))
|
||||
stacks[mm.group(2)] = float(mm.group(3))
|
||||
mb = re.search(r'Seat #(\d+) is the button', hh)
|
||||
button = int(mb.group(1)) if mb else None
|
||||
mbb = re.search(r'\(\$([0-9.]+)/\$([0-9.]+)', hh)
|
||||
sb, bb = (float(mbb.group(1)), float(mbb.group(2))) if mbb else (0.01, 0.02)
|
||||
shown = {}
|
||||
for mm in re.finditer(r'^(\S+): shows \[([^\]]+)\]', hh, re.M):
|
||||
shown[mm.group(1)] = mm.group(2).split()
|
||||
for mm in re.finditer(r'^Seat \d+: (\S+) showed \[([^\]]+)\]', hh, re.M):
|
||||
shown.setdefault(mm.group(1), mm.group(2).split())
|
||||
|
||||
if HERO not in seats:
|
||||
return None
|
||||
return {"hid": hid, "hero_cards": hero_cards, "hh": hh, "decisions": decisions,
|
||||
"prof": prof, "seats": seats, "stacks": stacks, "button": button,
|
||||
"sb": sb, "bb": bb, "shown": shown}
|
||||
|
||||
|
||||
def _seat_name(seats):
|
||||
return {v: k for k, v in seats.items()}
|
||||
|
||||
|
||||
def reconstruct(hand):
|
||||
"""Laeuft die HH-Aktionen durch, baut vor jeder Hero-Aktion den Wire-Spot und paart ihn
|
||||
mit der naechsten geloggten Entscheidung. Gibt Liste von (spot_dict, decision) zurueck."""
|
||||
seats, stacks = hand["seats"], hand["stacks"]
|
||||
bb = hand["bb"]
|
||||
hero_seat = seats[HERO]
|
||||
lines = hand["hh"].splitlines()
|
||||
street = "PREFLOP"
|
||||
street_contrib = Counter()
|
||||
cum = Counter()
|
||||
folded = set()
|
||||
history = []
|
||||
decisions = iter(hand["decisions"])
|
||||
out = []
|
||||
|
||||
def snapshot(dec):
|
||||
"""Baut die Wire-Anfrage fuer die aktuelle Hero-Entscheidung."""
|
||||
board = dec["board"]
|
||||
to_call = dec["to_call"]
|
||||
hero_stack = round(stacks[HERO] - cum[HERO], 4)
|
||||
legal = (["FOLD", "CALL"] + (["RAISE"] if hero_stack > to_call else [])) if to_call > 0 \
|
||||
else ["CHECK"] + (["RAISE"] if hero_stack > 0 else [])
|
||||
vils = []
|
||||
for name, seat in seats.items():
|
||||
if name == HERO:
|
||||
continue
|
||||
v = {"seat": seat, "stack": round(stacks[name] - cum[name], 4),
|
||||
"folded": seat in folded}
|
||||
if name in hand["prof"]:
|
||||
v["profile"] = dict(hand["prof"][name])
|
||||
vils.append(v)
|
||||
req = {"variant": "NLHE", "bigBlind": bb, "seats": len(seats), "heroSeat": hero_seat,
|
||||
"heroCards": _wire_cards(" ".join(hand["hero_cards"])),
|
||||
"board": _board_dict(board), "street": dec["street"],
|
||||
"pot": dec["pot"], "toCall": to_call, "heroStack": max(hero_stack, 0.0),
|
||||
"legalActions": legal, "allowedSizes": [],
|
||||
"villains": vils, "history": list(history),
|
||||
"seed": (int(hand["hid"]) + STREETS.index(dec["street"]) * 7 + len(out)) & 0xFFFFFFFF}
|
||||
if hand["button"]:
|
||||
req["buttonSeat"] = hand["button"]
|
||||
return req
|
||||
|
||||
for ln in lines:
|
||||
if ln.startswith("*** FLOP"):
|
||||
street = "FLOP"; street_contrib = Counter()
|
||||
elif ln.startswith("*** TURN"):
|
||||
street = "TURN"; street_contrib = Counter()
|
||||
elif ln.startswith("*** RIVER"):
|
||||
street = "RIVER"; street_contrib = Counter()
|
||||
elif ln.startswith("*** SHOW DOWN") or ln.startswith("*** SUMMARY"):
|
||||
break
|
||||
m = ACT_RE.match(ln)
|
||||
if not m:
|
||||
continue
|
||||
name, verb, amt, raise_to = m.group(1), m.group(2), m.group(3), m.group(4)
|
||||
if name not in seats:
|
||||
continue
|
||||
seat = seats[name]
|
||||
|
||||
# Vor Heros Aktion: Spot bauen und mit der naechsten Entscheidung paaren
|
||||
if name == HERO and verb in ("folds", "checks", "calls"):
|
||||
dec = next(decisions, None)
|
||||
if dec is not None and dec["street"] == street:
|
||||
out.append((snapshot(dec), dec))
|
||||
|
||||
# Aktion auf den Zustand anwenden + history fortschreiben
|
||||
if verb == "posts small blind":
|
||||
street_contrib[seat] = float(amt); cum[seat] += float(amt)
|
||||
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_SB", "amount": float(amt)})
|
||||
elif verb == "posts big blind":
|
||||
street_contrib[seat] = float(amt); cum[seat] += float(amt)
|
||||
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_BB", "amount": float(amt)})
|
||||
elif verb == "posts the ante":
|
||||
cum[seat] += float(amt)
|
||||
history.append({"street": "PREFLOP", "seat": seat, "action": "POST_ANTE", "amount": float(amt)})
|
||||
elif verb == "folds":
|
||||
folded.add(seat)
|
||||
history.append({"street": street, "seat": seat, "action": "FOLD"})
|
||||
elif verb == "checks":
|
||||
history.append({"street": street, "seat": seat, "action": "CHECK"})
|
||||
elif verb == "bets":
|
||||
street_contrib[seat] = float(amt); cum[seat] += float(amt)
|
||||
history.append({"street": street, "seat": seat, "action": "BET", "amount": float(amt)})
|
||||
elif verb == "calls":
|
||||
street_contrib[seat] += float(amt); cum[seat] += float(amt)
|
||||
history.append({"street": street, "seat": seat, "action": "CALL", "amount": round(street_contrib[seat], 4)})
|
||||
elif verb == "raises":
|
||||
add = float(raise_to) - street_contrib[seat]
|
||||
street_contrib[seat] = float(raise_to); cum[seat] += add
|
||||
history.append({"street": street, "seat": seat, "action": "RAISE", "amount": float(raise_to)})
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Benчmark
|
||||
def run(export_path):
|
||||
md = open(export_path, encoding="utf-8").read()
|
||||
blocks = re.split(r'^### Hand ', md, flags=re.M)[1:]
|
||||
hands = [h for h in (parse_hand(b) for b in blocks) if h]
|
||||
|
||||
spots = [] # (hand, spot_dict, logged_decision)
|
||||
for h in hands:
|
||||
for spot, dec in reconstruct(h):
|
||||
spots.append((h, spot, dec))
|
||||
|
||||
requests = [json.dumps(s[1]) for s in spots]
|
||||
answers = decide.entscheide(requests)
|
||||
|
||||
# --- Masse sammeln ---
|
||||
treue = 0; treue_bet = 0; n_bet = 0
|
||||
foldbet = Counter(); callbet = Counter()
|
||||
mdf_rows = []
|
||||
bias = []
|
||||
overfold_loss = 0.0; overcall_loss = 0.0
|
||||
overfolds = []
|
||||
for (h, spot, dec), ans in zip(spots, answers):
|
||||
re_act = ans.get("action", "ABSTAIN")
|
||||
re_eq = ans.get("equity")
|
||||
logged = dec["action"]
|
||||
# ABSTAIN zaehlt fuer die Treue als die Linie, die live gespielt wurde (Aussetzen -> Log)
|
||||
if re_act == logged:
|
||||
treue += 1
|
||||
facing = dec["street"] != "PREFLOP" and dec["to_call"] > 0
|
||||
if facing:
|
||||
n_bet += 1
|
||||
if re_act == logged:
|
||||
treue_bet += 1
|
||||
if re_act == "FOLD":
|
||||
foldbet[dec["street"]] += 1
|
||||
elif re_act == "CALL":
|
||||
callbet[dec["street"]] += 1
|
||||
# Ground Truth: lebende Gegner, die ihre Karten zeigen
|
||||
board = dec["board"]
|
||||
live_shown = []
|
||||
sn = _seat_name(h["seats"])
|
||||
for name, cs in h["shown"].items():
|
||||
if name == HERO:
|
||||
continue
|
||||
cc = karten(cs)
|
||||
if all(c not in karten(board) and c not in karten(" ".join(h["hero_cards"])) for c in cc):
|
||||
live_shown.append(cs)
|
||||
if live_shown:
|
||||
te = equity_vs(" ".join(h["hero_cards"]), board, live_shown)
|
||||
be = dec["to_call"] / (dec["pot"] + dec["to_call"])
|
||||
ev_call = te * (dec["pot"] + dec["to_call"]) - dec["to_call"]
|
||||
if re_eq is not None:
|
||||
bias.append(re_eq - te)
|
||||
if re_act == "FOLD" and ev_call > 1e-9:
|
||||
overfold_loss += ev_call
|
||||
overfolds.append((h["hid"], dec["street"], " ".join(board), dec["pot"],
|
||||
dec["to_call"], round(te, 3), round(be, 3), re_eq,
|
||||
" / ".join(" ".join(cs) for cs in live_shown), ev_call))
|
||||
elif re_act == "CALL" and ev_call < -1e-9:
|
||||
overcall_loss += -ev_call
|
||||
mdf_rows.append((dec["street"], dec["to_call"] / (dec["pot"] + dec["to_call"])))
|
||||
|
||||
bb = hands[0]["bb"] if hands else 0.02
|
||||
import statistics
|
||||
return {
|
||||
"n_hands": len(hands), "n_spots": len(spots), "n_bet": n_bet,
|
||||
"treue": treue / len(spots) if spots else 0,
|
||||
"treue_bet": treue_bet / n_bet if n_bet else 0,
|
||||
"foldbet": dict(foldbet), "callbet": dict(callbet),
|
||||
"bias_mean": statistics.mean(bias) if bias else 0.0,
|
||||
"bias_n": len(bias),
|
||||
"overfold_bb": overfold_loss / bb, "overcall_bb": overcall_loss / bb,
|
||||
"overfolds": sorted(overfolds, key=lambda x: -x[9]),
|
||||
"bb": bb,
|
||||
}
|
||||
|
||||
|
||||
def write_baseline(r, path, export_name):
|
||||
import subprocess
|
||||
try:
|
||||
sha = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=os.path.dirname(path) or ".",
|
||||
capture_output=True, text=True).stdout.strip() or "?"
|
||||
except Exception:
|
||||
sha = "?"
|
||||
lines = [f"label {sha}+lokal", f"export {export_name}",
|
||||
f"hands {r['n_hands']}", f"spots {r['n_spots']}", f"facing_bet {r['n_bet']}",
|
||||
f"faithfulness {r['treue']:.3f}", f"faithfulness_bet {r['treue_bet']:.3f}"]
|
||||
for s in ["FLOP", "TURN", "RIVER"]:
|
||||
lines.append(f"foldbet_{s.lower()} {r['foldbet'].get(s,0)} {r['callbet'].get(s,0)}")
|
||||
lines += [f"equity_bias {r['bias_mean']:.3f} n={r['bias_n']}",
|
||||
f"overfold_bb {r['overfold_bb']:.1f}", f"overcall_bb {r['overcall_bb']:.1f}"]
|
||||
open(path, "w", encoding="utf-8").write("\n".join(lines) + "\n")
|
||||
|
||||
|
||||
def main():
|
||||
path = os.environ.get("COINPOKER_EXPORT") or (sys.argv[1] if len(sys.argv) > 1 else None)
|
||||
if not path or not os.path.exists(path):
|
||||
print(f"Export nicht gefunden: {path}\nSetze COINPOKER_EXPORT=/pfad/zur/session.md (oder als Argument)")
|
||||
sys.exit(2)
|
||||
r = run(path)
|
||||
print(f"=== Replay-Benchmark ({os.path.basename(path)}) ===")
|
||||
print(f"Haende {r['n_hands']} | Hero-Entscheidungen rekonstruiert {r['n_spots']} | davon gegen Bet {r['n_bet']}")
|
||||
print(f"TREUE (Re-Decision == Log): gesamt {100*r['treue']:.0f}% | gegen Bet {100*r['treue_bet']:.0f}%")
|
||||
print()
|
||||
print("FOLD gegen Bet je Street (Re-Decision der aktuellen Engine):")
|
||||
for s in ["FLOP", "TURN", "RIVER"]:
|
||||
f, c = r["foldbet"].get(s, 0), r["callbet"].get(s, 0)
|
||||
if f + c:
|
||||
print(f" {s:5}: fold {f}, call {c} -> {100*f/(f+c):.0f}% Fold-to-bet")
|
||||
print()
|
||||
print(f"EQUITY-BIAS (Engine - wahr) ueber {r['bias_n']} Ground-Truth-Spots: {r['bias_mean']:+.3f}"
|
||||
f" (negativ = unterschaetzt -> Overfold-Wurzel)")
|
||||
print(f"EV-VERLUST belegt: Overfold {r['overfold_bb']:.1f} bb | Overcall {r['overcall_bb']:.1f} bb")
|
||||
print()
|
||||
print("Belegte Overfolds (Gegner gezeigt, wahre Equity machte den Call +EV):")
|
||||
for o in r["overfolds"][:12]:
|
||||
hid, st, bd, pot, tc, te, be, eq, vil, ev = o
|
||||
print(f" #{hid} {st:5} [{bd:14}] pot {pot:.2f} call {tc:.2f} | wahr {te:.2f} vs be {be:.2f} "
|
||||
f"| Engine {eq} | Gegner {vil} | +EV weg {ev/r['bb']:.1f} bb")
|
||||
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "benchmarks", "replay_baseline.txt")
|
||||
ename = re.sub(r'_analyse\.md$|\.md$', '', os.path.basename(path))
|
||||
write_baseline(r, base, ename)
|
||||
print(f"\nBaseline geschrieben: {os.path.normpath(base)}")
|
||||
return r
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Diagnose: woher kommt der Equity-Bias? Fuer jeden Wire-Spot von stdin wird die MODELLIERTE
|
||||
//! Gegner-Range gedumpt und Heros Equity dagegen gemessen - einmal wie die Engine sie baut und
|
||||
//! dann mit hochgedrehtem `bluff_share` je Continuation. Die Kurve zeigt, wie viel des Overfolds
|
||||
//! an der (zu GTO-balancierten) Bluff-Annahme haengt.
|
||||
//!
|
||||
//! cat spots.ndjson | cargo run --release --example diag_bluff
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use rechner::card::Card;
|
||||
use rechner::engine::range_combos::{as_ranges, combos};
|
||||
use rechner::engine::range_filter::{range_filter, HandFilter};
|
||||
use rechner::equity::monte_carlo::estimate;
|
||||
use rechner::equity::query::Query;
|
||||
use rechner::exploit::range_model::range_spec;
|
||||
use rechner::exploit::range_spec::RangeSpec;
|
||||
use rechner::game::Spot;
|
||||
use rechner::rng::Rng;
|
||||
|
||||
const TRIALS: u32 = 40_000; // hohe Trials -> Standardfehler ~0.0025, der Bias ist sichtbar
|
||||
|
||||
fn specs(spot: &Spot, bluff: Option<f64>) -> Vec<RangeSpec> {
|
||||
spot.live_villains()
|
||||
.map(|v| {
|
||||
let mut s = range_spec(spot, v);
|
||||
if let Some(b) = bluff {
|
||||
for c in s.continues.iter_mut() {
|
||||
c.bluff_share = b;
|
||||
}
|
||||
}
|
||||
s
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hero_share(spot: &Spot, bluff: Option<f64>) -> f64 {
|
||||
let rules = spot.rules();
|
||||
let specs = specs(spot, bluff);
|
||||
let filters: Vec<HandFilter> = specs
|
||||
.iter()
|
||||
.map(|s| range_filter(s, rules, spot.variant, &spot.board))
|
||||
.collect();
|
||||
if filters.is_empty() {
|
||||
return f64::NAN;
|
||||
}
|
||||
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
|
||||
let lists: Vec<_> = filters.iter().map(|f| combos(&rules, f, &dead)).collect();
|
||||
let ranges = as_ranges(&filters, &lists);
|
||||
let query = Query { rules, hero: &spot.hero_cards, board: &spot.board, villains: &ranges, trials: TRIALS };
|
||||
estimate(&query, Rng::seeded(spot.seed)).map(|(e, _)| e.share).unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
fn fmt_cards(cs: &[Card]) -> String {
|
||||
cs.iter().map(|c| format!("{c:?}")).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn diagnose(spot: &Spot) {
|
||||
println!(
|
||||
"--- {:?} [{}] | hero [{}] | pot {:.2} call {:.2} ---",
|
||||
spot.street,
|
||||
fmt_cards(&spot.board),
|
||||
fmt_cards(&spot.hero_cards),
|
||||
spot.pot,
|
||||
spot.to_call
|
||||
);
|
||||
for v in spot.live_villains() {
|
||||
let s = range_spec(spot, v);
|
||||
let conts: Vec<String> = s
|
||||
.continues
|
||||
.iter()
|
||||
.map(|c| format!("len{} >={:?} draws={} bluff={:.2}", c.board_len, c.min_made, c.draws_continue, c.bluff_share))
|
||||
.collect();
|
||||
println!(" villain seat {}: band [{:.2}..{:.2}] {}", v.seat, s.lo, s.hi, conts.join(" | "));
|
||||
}
|
||||
let base = hero_share(spot, None);
|
||||
println!(" hero equity (Modell wie gebaut): {base:.3}");
|
||||
print!(" bei bluff_share =");
|
||||
for b in [0.15, 0.30, 0.45, 0.60, 0.75, 0.90] {
|
||||
print!(" {:.2}->{:.3}", b, hero_share(spot, Some(b)));
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_to_string(&mut input).expect("stdin");
|
||||
for line in input.lines().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
match rechner::json::parse(line).and_then(|v| rechner::wire::decode::decode(&v)) {
|
||||
Ok(spot) => diagnose(&spot),
|
||||
Err(e) => eprintln!("decode failed: {e} on: {}", &line[..line.len().min(80)]),
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -34,7 +34,7 @@ fn trials(spot: &Spot) -> u32 {
|
||||
|
||||
/// Postflop: read the hand, model each villain's range, simulate against it and
|
||||
/// against the hands that would call each raise, choose.
|
||||
fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision {
|
||||
fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot) -> Decision {
|
||||
let rules = spot.rules();
|
||||
let hand_read = match read(&rules, &spot.hero_cards, &spot.board) {
|
||||
Ok(r) => r,
|
||||
@@ -62,8 +62,12 @@ fn postflop(spot: &Spot, thresholds: &Thresholds) -> Decision {
|
||||
};
|
||||
match estimate(&query, Rng::seeded(spot.seed)) {
|
||||
Ok((equity, _)) => {
|
||||
choose_postflop_with(spot, &equity, &called_equity(spot), thresholds, &hand_read)
|
||||
.with_equity(equity.share)
|
||||
// GTO-Boden UEBER dem Modell, aber unter der Exploit-Range: ein modellgetriebener
|
||||
// River-Fold einer verteidigungswuerdigen Made-Hand wird zum MDF-Call. `raw` traegt die
|
||||
// UNGEGATETEN Reads - der Boden darf den Gegner-Bluffanteil defensiv lesen (gegen einen
|
||||
// bewiesenen Nicht-Bluffer mehr folden), was `read_gate` dem Range-Modell verwehrt.
|
||||
let base = choose_postflop_with(spot, &equity, &called_equity(spot), thresholds, &hand_read);
|
||||
crate::exploit::mdf_floor::floor(raw, hand_read.made, base).with_equity(equity.share)
|
||||
}
|
||||
Err(fault) => Decision::abstain(format!("equity unavailable: {fault}")),
|
||||
}
|
||||
@@ -82,7 +86,7 @@ fn with_premium(thresholds: Thresholds, premium: f64) -> Thresholds {
|
||||
}
|
||||
}
|
||||
|
||||
fn think(spot: &Spot, premium: f64, jam_widen: f64) -> Decision {
|
||||
fn think(spot: &Spot, premium: f64, jam_widen: f64, raw: &Spot) -> Decision {
|
||||
let profiles: Vec<Profile> = spot.live_villains().filter_map(|v| v.profile).collect();
|
||||
let thresholds = with_premium(adjust(Thresholds::BASE, &profiles), premium);
|
||||
match spot.street {
|
||||
@@ -93,7 +97,7 @@ fn think(spot: &Spot, premium: f64, jam_widen: f64) -> Decision {
|
||||
let certainty = plan.certainty.max(MIN_CERTAINTY);
|
||||
from_plan(spot, &PreflopPlan { certainty, ..plan })
|
||||
}
|
||||
Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds),
|
||||
Street::Flop | Street::Turn | Street::River => postflop(spot, &thresholds, raw),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +114,7 @@ pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
|
||||
// Only act on reads we are proven to beat blind play with (`read_gate`); competent and
|
||||
// aggressive opponents are played blind until the exploit logic earns them on the ladder.
|
||||
let gated = super::read_gate::gate_reads(spot);
|
||||
let raw = spot; // ungated reads, used ONLY by the defensive MDF floor (mdf_floor::floor)
|
||||
let spot = &gated;
|
||||
let premium = match lage.map(|l| call_premium(spot, l)) {
|
||||
None => 0.0,
|
||||
@@ -119,7 +124,7 @@ pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
|
||||
// Open-Jam-Weitung an der Bubble (`icm::risk::jam_pressure`): nur bei Turnierlage, sonst neutral.
|
||||
// Unpricebar -> 1.0 (keine Weitung), nie ein Abbruch - der Riegel liegt bei `premium`/Calls.
|
||||
let jam_widen = lage.and_then(|l| jam_pressure(spot, l)).map(jam_width_factor).unwrap_or(1.0);
|
||||
let decision = enforce(spot, think(spot, premium, jam_widen));
|
||||
let decision = enforce(spot, think(spot, premium, jam_widen, raw));
|
||||
match crate::hand::showdown::best(spot.rules().hole_usage, &spot.hero_cards, &spot.board) {
|
||||
Ok(strength) => decision.with_category(strength.category),
|
||||
Err(_) => decision,
|
||||
|
||||
@@ -17,6 +17,12 @@ pub const MAX_BLUFF_SHARE: f64 = 0.6;
|
||||
const AVERAGE_AGGRESSION: f64 = 0.45;
|
||||
const MAX_FACTOR: f64 = 2.0;
|
||||
|
||||
/// Populations-Ueber-Bluff-Prior gegen einen UNGELESENEN Gegner: der Micro-Pool c-bettet/barrelt
|
||||
/// weit ueber GTO-Balance, also bekommt eine unbekannte (auch auf blind gegatete) Range auf
|
||||
/// Flop/Turn mindestens diesen Bluff-Anteil. River bleibt dem MDF-Boden ueberlassen.
|
||||
/// Micro-Prior; spaeter stake-skaliert.
|
||||
const POP_BLUFF_PRIOR: [f64; 4] = [0.0, 0.40, 0.35, 0.0]; // preflop, flop, turn, river
|
||||
|
||||
fn street_factor(street: Street) -> f64 {
|
||||
match street {
|
||||
Street::Preflop => 0.0,
|
||||
@@ -45,3 +51,17 @@ pub fn bluff_share(profile: Option<&Profile>, ratio: Option<f64>, street: Street
|
||||
let balanced = s / (1.0 + 2.0 * s);
|
||||
(balanced * street_factor(street) * style_factor(profile)).clamp(0.0, MAX_BLUFF_SHARE)
|
||||
}
|
||||
|
||||
/// Lift the population over-bluff prior onto a base bluff share. It applies ONLY to an UNREAD
|
||||
/// villain (`profile` None - including a read gated to blind) on a FIRST barrel: a sustained
|
||||
/// multi-street line (`sustained`, the villain already bet/raised an earlier street) is
|
||||
/// value-weighted even in the micro pool, so it gets no bump. River and preflop carry no prior
|
||||
/// (the river is the MDF floor's job). Never exceeds `MAX_BLUFF_SHARE`.
|
||||
pub fn with_pop_prior(profile: Option<&Profile>, street: Street, sustained: bool, base: f64) -> f64 {
|
||||
let prior = if profile.is_none() && !sustained {
|
||||
POP_BLUFF_PRIOR[street as usize]
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
base.max(prior).min(MAX_BLUFF_SHARE)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Minimum-defence-frequency floor: on the river, a made hand in the top `1 - alpha` of a
|
||||
//! defensible range is never folded to a bet, whatever the opponent range model says.
|
||||
//!
|
||||
//! This is the GTO floor UNDER the exploit deviation. Facing a bet of break-even `alpha`
|
||||
//! (`to_call / (pot + to_call)`), a defender who folds more than `1 - alpha` of the hands that
|
||||
//! beat a bluff lets the bettor print with any air (MDF). The engine's villain range model is
|
||||
//! measured to be too value-heavy (replay benchmark: mean equity bias ~-0.22, river fold-to-bet
|
||||
//! ~86 %), so equity-against-the-model folds bluff-catchers that MDF says must defend. This floor
|
||||
//! reads HERO's own made hand - not the (untrusted) villain range - so it can never be moved by a
|
||||
//! miscalibrated read: it only ever turns a model-driven fold into the call MDF requires.
|
||||
//!
|
||||
//! River only: there the bet is terminal and MDF is exact (no draws, no future streets, realisation
|
||||
//! 1.0). Flop and turn defence couples with realisation and is left to the equity line.
|
||||
|
||||
use crate::exploit::profile::Profile;
|
||||
use crate::exploit::style::{classify, Style};
|
||||
use crate::game::{ActionKind, Choice, Decision, Spot, Street};
|
||||
use crate::odds::break_even::break_even;
|
||||
use crate::read::made::Made;
|
||||
|
||||
/// Below this observed postflop aggression frequency the bettor's range is treated as bluff-light.
|
||||
const BLUFF_LIGHT_AGGRESSION: f64 = 0.25;
|
||||
|
||||
/// Fraction of random hands hero's made class beats by showdown - the MDF yardstick (rough,
|
||||
/// monotone in `Made`). Not an equity: only its order and rough level matter, to place the hand
|
||||
/// in hero's range (`strength >= alpha` ⇔ top `1 - alpha`).
|
||||
fn strength(made: Made) -> f64 {
|
||||
match made {
|
||||
Made::Air => 0.15,
|
||||
Made::BoardOnly => 0.18,
|
||||
Made::Underpair => 0.42,
|
||||
Made::BottomPair => 0.50,
|
||||
Made::MiddlePair => 0.60,
|
||||
Made::TopPairWeakKicker => 0.70,
|
||||
Made::TopPairGoodKicker => 0.80,
|
||||
Made::Overpair => 0.85,
|
||||
Made::TwoPair => 0.90,
|
||||
Made::Set | Made::Trips => 0.95,
|
||||
Made::Straight => 0.97,
|
||||
Made::Flush => 0.98,
|
||||
Made::FullHouse => 0.99,
|
||||
Made::Quads => 0.995,
|
||||
Made::StraightFlush => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand with real showdown value: at least a pair, so it beats a pure bluff. `BoardOnly`
|
||||
/// (hero plays the board, chops at best) and `Air` are not bluff-catchers and are excluded -
|
||||
/// their MDF defence, if any, is a raise, never a call.
|
||||
fn beats_bluffs(made: Made) -> bool {
|
||||
made >= Made::Underpair
|
||||
}
|
||||
|
||||
/// Positive, directly observed evidence that this bettor's range is bluff-light, so MDF does not
|
||||
/// require defence against it: a low postflop aggression frequency, or the nit style. Reads the
|
||||
/// robust observed FREQUENCY (`aggression`, vpip/pfr/fold), never the miscalibrated range model -
|
||||
/// the only thing allowed to switch the floor off is a bettor we have *seen* under-bluff.
|
||||
fn under_bluffs(profile: &Profile) -> bool {
|
||||
profile.aggression.is_some_and(|a| a < BLUFF_LIGHT_AGGRESSION) || classify(profile) == Style::Nit
|
||||
}
|
||||
|
||||
/// Could the bet contain bluffs? Yes unless every live villain is a confirmed under-bluffer. An
|
||||
/// unknown villain (no profile) counts as a possible bluffer, so the floor still defends against
|
||||
/// the (bluff-heavy) unread micro population; only a read that says "this bettor doesn't bluff"
|
||||
/// turns it off.
|
||||
fn range_may_bluff(spot: &Spot) -> bool {
|
||||
let mut live = spot.villains.iter().filter(|v| !v.folded).peekable();
|
||||
live.peek().is_none()
|
||||
|| live.any(|v| v.profile.as_ref().is_none_or(|p| !under_bluffs(p)))
|
||||
}
|
||||
|
||||
/// True when hero must defend `made` against the bet he faces (never fold): on the river, with
|
||||
/// a bluff-catcher or better, whose strength puts it in the top `1 - alpha` of the range, and the
|
||||
/// bettor is not a confirmed under-bluffer.
|
||||
pub fn defends(spot: &Spot, made: Made) -> bool {
|
||||
spot.street == Street::River
|
||||
&& spot.to_call > 0.0
|
||||
&& beats_bluffs(made)
|
||||
&& strength(made) >= break_even(spot.pot, spot.to_call)
|
||||
&& range_may_bluff(spot)
|
||||
}
|
||||
|
||||
/// Overlay the floor on a finished postflop decision: a model-driven river fold of a defensible
|
||||
/// made hand becomes the call MDF requires. `spot` must carry the UNGATED villain reads - the
|
||||
/// floor's defensive use of a read (fold more against a confirmed non-bluffer, never fold a
|
||||
/// bluff-catcher the model mis-prices) is always safe, unlike the range model that `read_gate`
|
||||
/// keeps blind. The base decision's EV annotations are kept; anything but a floorable river fold
|
||||
/// is returned unchanged.
|
||||
pub fn floor(spot: &Spot, made: Made, decision: Decision) -> Decision {
|
||||
if decision.choice == Choice::Fold && spot.is_legal(ActionKind::Call) && defends(spot, made) {
|
||||
let be = break_even(spot.pot, spot.to_call);
|
||||
return Decision::new(
|
||||
Choice::Call,
|
||||
0.5,
|
||||
format!("MDF-Boden: Made-Hand verteidigt - Modell-Fold uebersteuert (break-even {be:.2})"),
|
||||
)
|
||||
.with_evs(decision.evs);
|
||||
}
|
||||
decision
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn river(pot: f64, to_call: f64) -> Spot {
|
||||
Spot {
|
||||
variant: crate::variant::Variant::Nlhe,
|
||||
big_blind: 0.1,
|
||||
seats: 2,
|
||||
hero_seat: 1,
|
||||
button_seat: None,
|
||||
hero_cards: crate::card::Card::parse_list("Kd 7d").unwrap(),
|
||||
board: crate::card::Card::parse_list("9c Tc Kc Qd 2h").unwrap(),
|
||||
street: Street::River,
|
||||
pot,
|
||||
to_call,
|
||||
hero_stack: 100.0,
|
||||
min_raise_to: None,
|
||||
max_raise_to: None,
|
||||
legal: vec![],
|
||||
allowed_sizes: None,
|
||||
villains: vec![],
|
||||
seed: 1,
|
||||
history: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_pair_defends_a_half_pot_river_bet() {
|
||||
// alpha = 0.26 / 0.83 = 0.31; top pair weak kicker strength 0.70 >= 0.31 -> defend
|
||||
assert!(defends(&river(0.57, 0.26), Made::TopPairWeakKicker));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_pair_folds_to_an_overbet() {
|
||||
// alpha = 15 / 25 = 0.60; underpair strength 0.42 < 0.60 -> no floor
|
||||
assert!(!defends(&river(10.0, 15.0), Made::Underpair));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn air_is_never_floored() {
|
||||
assert!(!defends(&river(10.0, 3.0), Made::Air));
|
||||
assert!(!defends(&river(10.0, 3.0), Made::BoardOnly));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_on_the_river() {
|
||||
let flop = Spot { street: Street::Flop, ..river(10.0, 3.0) };
|
||||
assert!(!defends(&flop, Made::TopPairGoodKicker));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_floor_without_a_bet() {
|
||||
assert!(!defends(&river(10.0, 0.0), Made::Overpair));
|
||||
}
|
||||
|
||||
fn villain(profile: Option<Profile>) -> crate::game::Villain {
|
||||
crate::game::Villain { seat: 1, stack: 100.0, folded: false, profile }
|
||||
}
|
||||
|
||||
fn prof(aggression: f64, vpip: f64, fold_to_bet: f64) -> Profile {
|
||||
Profile {
|
||||
aggression: Some(aggression),
|
||||
vpip: Some(vpip),
|
||||
fold_to_bet: Some(fold_to_bet),
|
||||
..Profile::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_aggressive_bettor_is_defended() {
|
||||
// alpha 0.33, middle pair 0.60 >= 0.33, and the maniac bets bluffs -> defend.
|
||||
let spot = Spot { villains: vec![villain(Some(prof(0.8, 0.55, 0.35)))], ..river(12.0, 6.0) };
|
||||
assert!(defends(&spot, Made::MiddlePair));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unread_bettor_is_defended() {
|
||||
// No profile: the unread micro population bluffs, so the floor still holds.
|
||||
let spot = Spot { villains: vec![villain(None)], ..river(12.0, 6.0) };
|
||||
assert!(defends(&spot, Made::MiddlePair));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_confirmed_under_bluffer_is_not_floored() {
|
||||
// Low observed aggression (0.0) and a nit: no bluffs to catch, the fold stands.
|
||||
let honest = Spot { villains: vec![villain(Some(prof(0.0, 0.25, 0.5)))], ..river(12.0, 6.0) };
|
||||
assert!(!defends(&honest, Made::MiddlePair));
|
||||
let nit = Spot { villains: vec![villain(Some(prof(0.15, 0.11, 0.8)))], ..river(12.0, 6.0) };
|
||||
assert!(!defends(&nit, Made::MiddlePair));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folded_under_bluffer_does_not_suppress_the_live_bettor() {
|
||||
// The nit folded; the live bettor is unread -> still defended.
|
||||
let nit = crate::game::Villain { folded: true, ..villain(Some(prof(0.15, 0.11, 0.8))) };
|
||||
let spot = Spot { villains: vec![nit, villain(None)], ..river(12.0, 6.0) };
|
||||
assert!(defends(&spot, Made::MiddlePair));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod fold_chance;
|
||||
pub mod fold_equity_scale;
|
||||
pub mod made_ladder;
|
||||
pub mod mark;
|
||||
pub mod mdf_floor;
|
||||
pub mod pot_trace;
|
||||
pub mod preflop_role;
|
||||
pub mod profile;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::bet_ratio::bet_ratios;
|
||||
use super::bluff_share::bluff_share;
|
||||
use super::bluff_share::{bluff_share, with_pop_prior};
|
||||
use super::made_ladder::rung;
|
||||
use super::range_spec::Continuation;
|
||||
use super::size_notch::size_notch;
|
||||
@@ -78,6 +78,17 @@ fn merge(a: Option<Floor>, b: Option<Floor>) -> Option<Floor> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Did the villain already bet or raise on an earlier postflop street? Such a line is a sustained
|
||||
/// barrel - value-weighted even in the micro pool - so it earns no population over-bluff prior.
|
||||
fn aggressed_earlier(history: &[ActionRecord], street: Street, seat: u8) -> bool {
|
||||
history.iter().any(|r| {
|
||||
r.seat == seat
|
||||
&& r.street != Street::Preflop
|
||||
&& (r.street as usize) < (street as usize)
|
||||
&& r.action.is_aggressive()
|
||||
})
|
||||
}
|
||||
|
||||
/// One continuation for the villain on `street`, if their actions there say anything.
|
||||
fn on_street(
|
||||
spot: &Spot,
|
||||
@@ -86,13 +97,15 @@ fn on_street(
|
||||
street: Street,
|
||||
) -> Option<Continuation> {
|
||||
let slot = street as usize - 1;
|
||||
let sustained = aggressed_earlier(&spot.history, street, villain.seat);
|
||||
let made_bet =
|
||||
own_aggression(&spot.history, ratios, street, villain.seat).map(|(lvl, ratio)| {
|
||||
let base = [BET_RUNG, RAISE_RUNG][lvl][slot];
|
||||
let bluff = bluff_share(villain.profile.as_ref(), ratio, street);
|
||||
(
|
||||
rung(base, size_notch(ratio) + style_rung(villain)),
|
||||
DRAWS[slot],
|
||||
bluff_share(villain.profile.as_ref(), ratio, street),
|
||||
with_pop_prior(villain.profile.as_ref(), street, sustained, bluff),
|
||||
)
|
||||
});
|
||||
let made_call = called_big_bet(&spot.history, ratios, street, villain.seat).then(|| {
|
||||
|
||||
+21
-3
@@ -18,14 +18,30 @@ pub struct Scenario {
|
||||
pub setup: Setup,
|
||||
}
|
||||
|
||||
const fn scenario(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
|
||||
const fn with_read(name: &'static str, players: u8, opponent: Opponent, blind: bool) -> Scenario {
|
||||
let deals = if players == 2 { HEADS_UP_DEALS } else { SIX_MAX_DEALS };
|
||||
Scenario { name, setup: Setup { players, opponent, deals, stack_bb: STACK_BB, seed: SEED } }
|
||||
Scenario { name, setup: Setup { players, opponent, deals, stack_bb: STACK_BB, seed: SEED, blind } }
|
||||
}
|
||||
|
||||
/// Read-given: the engine sees the opponent's converged HUD read (the exploit brain).
|
||||
const fn scenario(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
|
||||
with_read(name, players, opponent, false)
|
||||
}
|
||||
|
||||
/// Blind: the read is withheld, the no-read baseline a memory / probe must improve on. The gap to
|
||||
/// the matching read-given scenario is the measured session payoff of a read (`tests/sim_blind`).
|
||||
const fn blind(name: &'static str, players: u8, opponent: Opponent) -> Scenario {
|
||||
with_read(name, players, opponent, true)
|
||||
}
|
||||
|
||||
/// Folder and random opponent are left out: the first is saturated at +75, the second's variance
|
||||
/// would drown the total. `tests/sim_strength.rs` keeps watching both.
|
||||
pub const SCENARIOS: [Scenario; 10] = [
|
||||
///
|
||||
/// The last two are blind variants of the two opponents the engine can actually exploit today (the
|
||||
/// calling station and the fish, the classes `exploit::read_gate` lets through): they measure what
|
||||
/// the engine wins against a leak it has not read yet. Stage 1 (session memory) turns a blind read
|
||||
/// into the matching read-given one over a session; its gain shows up as Better on these two.
|
||||
pub const SCENARIOS: [Scenario; 12] = [
|
||||
scenario("heads-up reg", 2, Opponent::Reader(Style::Reg)),
|
||||
scenario("heads-up nit", 2, Opponent::Reader(Style::Nit)),
|
||||
scenario("heads-up maniac", 2, Opponent::Reader(Style::Maniac)),
|
||||
@@ -36,6 +52,8 @@ pub const SCENARIOS: [Scenario; 10] = [
|
||||
scenario("6-max maniac", 6, Opponent::Reader(Style::Maniac)),
|
||||
scenario("6-max fish", 6, Opponent::Reader(Style::Fish)),
|
||||
scenario("6-max calling station", 6, Opponent::CallingStation),
|
||||
blind("heads-up fish (blind)", 2, Opponent::Reader(Style::Fish)),
|
||||
blind("heads-up calling station (blind)", 2, Opponent::CallingStation),
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -14,6 +14,10 @@ pub struct Setup {
|
||||
pub deals: u32,
|
||||
pub stack_bb: f64,
|
||||
pub seed: u64,
|
||||
/// Withhold the opponent's HUD read: the engine plays the hand blind (no profile), the way it
|
||||
/// sees an opponent it has not read yet. The gap to the same scenario read-given is the session
|
||||
/// payoff a memory / probe would earn (`sim::reads`, `tests/sim_blind`).
|
||||
pub blind: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -103,6 +107,7 @@ fn deal_samples_at(setup: &Setup, cost: TableCost) -> (Vec<f64>, Measurement) {
|
||||
opponent: setup.opponent,
|
||||
stack_bb: setup.stack_bb,
|
||||
seed: mix(setup.seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64),
|
||||
blind: setup.blind,
|
||||
}, cost);
|
||||
rake += r.rake;
|
||||
sum += r.hero_net - r.luck;
|
||||
|
||||
+9
-2
@@ -55,6 +55,8 @@ pub struct HandSetup<'a> {
|
||||
pub stack_bb: f64,
|
||||
/// Seeds the opponents' choices and the engine's `seed` field.
|
||||
pub seed: u64,
|
||||
/// Withhold the opponent's read: the engine plays the hand blind (no profile). See `Setup`.
|
||||
pub blind: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -173,8 +175,13 @@ impl Table<'_> {
|
||||
legal.push(ActionKind::Raise);
|
||||
}
|
||||
// The engine sees the opponents the way a converged HUD would (`sim::reads`), so the ladder
|
||||
// measures the exploit brain instead of playing it blind.
|
||||
let read = super::reads::opponent_profile(self.setup.opponent);
|
||||
// measures the exploit brain instead of playing it blind - unless the scenario withholds the
|
||||
// read (`blind`), to measure the no-read baseline a memory / probe would improve on.
|
||||
let read = if self.setup.blind {
|
||||
None
|
||||
} else {
|
||||
super::reads::opponent_profile(self.setup.opponent)
|
||||
};
|
||||
let villains = (0..self.players())
|
||||
.filter(|j| *j != i)
|
||||
.map(|j| Villain { seat: j as u8 + 1, stack: self.stack[j], folded: self.folded[j], profile: read })
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay-Benchmark: Evaluator, HH-Parser und Spot-Rekonstruktion.
|
||||
|
||||
Der unabhaengige Evaluator (`eval7`) ist der Ground Truth des Benchmarks - er wird hier gegen
|
||||
bekannte Haende geprueft. Parser und Rekonstruktion laufen auf einer eingebetteten Mini-Session
|
||||
(Format wie der echte Export), deterministisch, ohne die Engine. Der Engine-Roundtrip wird nur
|
||||
geprueft, wenn das Binary schon gebaut ist (sonst uebersprungen - die schnelle Spur baut nicht).
|
||||
|
||||
python3 tests/replay_spec.py -v
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
HIER = os.path.dirname(os.path.abspath(__file__))
|
||||
WURZEL = os.path.dirname(HIER)
|
||||
sys.path.insert(0, os.path.join(WURZEL, "entscheiden"))
|
||||
|
||||
import eval7
|
||||
import replay
|
||||
|
||||
# Eine Mini-Session im echten Export-Format: eine Hand, in der Hero (mmintel) Bottom Pair + Ass
|
||||
# gegen eine Bet foldet und der Gegner J-high als Bluff zeigt - der belegte Overfold.
|
||||
FIXTURE = """# CoinPoker Cash Game Export (Fixture)
|
||||
|
||||
### Hand #999000000001 - 2026-11-10 10:00:00 CET - `Test NL 0.01-0.02` - Net: **-0.06 (-3.0 bb)**
|
||||
|
||||
- **Players (BTN S6):** S1 aha09 ($0.96, VPIP 0%/2h), S2 mmintel ($2.03, VPIP 0%/1h), S3 zambino78 ($0.42, VPIP 28%/82h), S6 Natalensis ($2.11, VPIP 45%/11h)
|
||||
- **Hero Hole Cards:** `As 2c`
|
||||
- **Engine Decisions:**
|
||||
- `PREFLOP` | board=`` | pot=$0.07 toCall=$0.02 | **CALL** | eq=None | BB vs open -> call
|
||||
- `FLOP` | board=`Kd 5s 2h` | pot=$0.09 toCall=$0.00 | **CHECK** | eq=0.418 | bottom pair
|
||||
- `FLOP` | board=`Kd 5s 2h` | pot=$0.15 toCall=$0.06 | **FOLD** | eq=0.246 | bottom pair: EV call -0.01
|
||||
|
||||
```text
|
||||
PokerStars Hand #999000000001: Hold'em No Limit ($0.01/$0.02 USD) - 2026/11/10 10:00:00 CET
|
||||
Table 'Test NL 0.01-0.02' 6-max Seat #6 is the button
|
||||
Seat 1: aha09 ($0.96 in chips)
|
||||
Seat 2: mmintel ($2.03 in chips)
|
||||
Seat 3: zambino78 ($0.42 in chips)
|
||||
Seat 6: Natalensis ($2.11 in chips)
|
||||
aha09: posts small blind $0.01
|
||||
mmintel: posts big blind $0.02
|
||||
*** HOLE CARDS ***
|
||||
Dealt to mmintel [As 2c]
|
||||
zambino78: raises $0.02 to $0.04
|
||||
Natalensis: folds
|
||||
aha09: folds
|
||||
mmintel: calls $0.02
|
||||
*** FLOP *** [Kd 5s 2h]
|
||||
mmintel: checks
|
||||
zambino78: bets $0.06
|
||||
mmintel: folds
|
||||
Uncalled bet ($0.06) returned to zambino78
|
||||
zambino78: shows [Jh 9h]
|
||||
zambino78 collected $0.09 from pot
|
||||
*** SUMMARY ***
|
||||
Total pot $0.09 | Rake $0.00
|
||||
Board [Kd 5s 2h]
|
||||
```
|
||||
"""
|
||||
|
||||
|
||||
class Evaluator(unittest.TestCase):
|
||||
def test_selbsttest_laeuft_beim_import(self):
|
||||
eval7._selftest() # wirft bei Fehler
|
||||
|
||||
def test_river_showdown_exakt(self):
|
||||
# Top Pair Koenige schlaegt Paar Zehnen auf fertigem Board -> Equity 1.0
|
||||
self.assertEqual(eval7.equity_vs("Kd 7d", "9c Tc Kc Qd 2h", ["Ah Td"]), 1.0)
|
||||
|
||||
def test_bottom_pair_ass_vs_bluff(self):
|
||||
# As2c Bottom Pair + Ass gegen Jh9h (J-high) auf Kd5s2h: klar vorn
|
||||
eq = eval7.equity_vs("As 2c", "Kd 5s 2h", ["Jh 9h"])
|
||||
self.assertGreater(eq, 0.6)
|
||||
|
||||
|
||||
class Parser(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.blocks = FIXTURE.split("### Hand ")[1:]
|
||||
self.hand = replay.parse_hand(self.blocks[0])
|
||||
|
||||
def test_hand_geparst(self):
|
||||
self.assertIsNotNone(self.hand)
|
||||
self.assertEqual(self.hand["hero_cards"], ["As", "2c"])
|
||||
self.assertEqual(self.hand["seats"]["mmintel"], 2)
|
||||
self.assertEqual(self.hand["button"], 6)
|
||||
self.assertEqual(self.hand["shown"]["zambino78"], ["Jh", "9h"])
|
||||
self.assertEqual(self.hand["prof"]["zambino78"], {"vpip": 0.28, "hands": 82})
|
||||
|
||||
def test_rekonstruktion_baut_wohlgeformte_spots(self):
|
||||
spots = replay.reconstruct(self.hand)
|
||||
# Drei Hero-Aktionen: Preflop CALL, Flop CHECK, Flop FOLD
|
||||
self.assertEqual(len(spots), 3)
|
||||
for req, dec in spots:
|
||||
for key in ("variant", "bigBlind", "heroSeat", "heroCards", "street",
|
||||
"pot", "toCall", "heroStack", "legalActions", "villains", "history"):
|
||||
self.assertIn(key, req)
|
||||
self.assertGreaterEqual(req["heroStack"], 0.0)
|
||||
|
||||
def test_history_vor_dem_flop_fold(self):
|
||||
spots = replay.reconstruct(self.hand)
|
||||
_, _ = spots[0]
|
||||
flop_fold_req, dec = spots[2]
|
||||
self.assertEqual(dec["action"], "FOLD")
|
||||
self.assertEqual(dec["to_call"], 0.06)
|
||||
# Die History vor dem Fold enthaelt die Bet des Gegners (zambino78 auf Sitz 3)
|
||||
bet = [h for h in flop_fold_req["history"] if h["action"] == "BET"]
|
||||
self.assertTrue(bet and bet[0]["seat"] == 3)
|
||||
# und Profil geht mit auf die Reise
|
||||
v3 = [v for v in flop_fold_req["villains"] if v["seat"] == 3][0]
|
||||
self.assertAlmostEqual(v3["profile"]["vpip"], 0.28)
|
||||
|
||||
|
||||
class EngineRoundtrip(unittest.TestCase):
|
||||
def test_engine_entscheidet_rekonstruierten_spot(self):
|
||||
import decide
|
||||
if not decide.bereit() or not decide.frisch():
|
||||
self.skipTest("Engine-Binary nicht frisch gebaut - schnelle Spur baut nicht")
|
||||
hand = replay.parse_hand(FIXTURE.split("### Hand ")[1:][0])
|
||||
import json
|
||||
req = json.dumps(replay.reconstruct(hand)[2][0])
|
||||
ans = decide.entscheide([req])[0]
|
||||
self.assertIn(ans.get("action"), {"FOLD", "CALL", "RAISE", "CHECK", "ABSTAIN"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -237,7 +237,7 @@ fn a_raise_is_never_offered_when_impossible() {
|
||||
fn reading_opponents_play_legal_hands_and_lose_chips_to_nobody() {
|
||||
for style in Style::ALL {
|
||||
for players in [2u8, 6] {
|
||||
let s = Setup { players, opponent: Opponent::Reader(style), deals: 4, stack_bb: 100.0, seed: 3 };
|
||||
let s = Setup { players, opponent: Opponent::Reader(style), deals: 4, stack_bb: 100.0, seed: 3, blind: false };
|
||||
let m = measure(&s);
|
||||
assert_eq!(m.invalid, 0, "{style:?} {players}");
|
||||
assert!(m.decisions > 0);
|
||||
@@ -247,7 +247,7 @@ fn reading_opponents_play_legal_hands_and_lose_chips_to_nobody() {
|
||||
|
||||
#[test]
|
||||
fn a_reading_opponent_does_not_play_like_a_blind_one() {
|
||||
let s = |opponent| Setup { players: 2, opponent, deals: 40, stack_bb: 100.0, seed: 3 };
|
||||
let s = |opponent| Setup { players: 2, opponent, deals: 40, stack_bb: 100.0, seed: 3, blind: false };
|
||||
assert_ne!(deal_samples(&s(Opponent::Reader(Style::Nit))).0, deal_samples(&s(Opponent::Reader(Style::Maniac))).0);
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ fn a_reading_opponent_does_not_play_like_a_blind_one() {
|
||||
|
||||
#[test]
|
||||
fn deal_samples_agree_with_the_measurement() {
|
||||
let s = Setup { players: 2, opponent: Opponent::RandomLegal, deals: 30, stack_bb: 100.0, seed: 9 };
|
||||
let s = Setup { players: 2, opponent: Opponent::RandomLegal, deals: 30, stack_bb: 100.0, seed: 9, blind: false };
|
||||
let (samples, _) = deal_samples(&s);
|
||||
let mean = samples.iter().sum::<f64>() / 30.0;
|
||||
assert_eq!(samples.len(), 30);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Stage 0: der Preis eines Reads ist messbar. Derselbe Gegner, dieselben Austeilungen - einmal
|
||||
//! mit seinem konvergierten HUD-Read (die Exploit-Hirn-Lage), einmal blind (ungelesen, wie Hand 1
|
||||
//! einer Sitzung). Die Differenz blind -> read-given ist der Sitzungsertrag, den ein Gedaechtnis
|
||||
//! oder eine Probe spaeter einspielt. Diese Spezifikation friert ein, dass der Preis positiv ist
|
||||
//! und dass Blindspiel nie besser als Lesen ist - gegen die zwei Klassen, die die Engine heute
|
||||
//! ueberhaupt ausbeuten kann (Calling Station und Fisch, siehe `exploit::read_gate`).
|
||||
|
||||
use rechner::sim::benchmark::{SCENARIOS};
|
||||
use rechner::sim::opponent::Opponent;
|
||||
use rechner::sim::paired::{compare, Verdict};
|
||||
use rechner::sim::reader::Style;
|
||||
use rechner::sim::session::{deal_samples, Setup};
|
||||
|
||||
const SEED: u64 = 0x5EED_0001;
|
||||
/// Dieselbe Austeilungszahl wie die Messlatte (heads-up), damit der Preis hier exakt der Luecke der
|
||||
/// Szenarien `heads-up fish` / `heads-up fish (blind)` entspricht und deterministisch ist.
|
||||
const DEALS: u32 = 1000;
|
||||
|
||||
/// (blind samples, read-given samples) fuer denselben Gegner und dieselben Austeilungen.
|
||||
fn paired(opponent: Opponent) -> (Vec<f64>, Vec<f64>) {
|
||||
let read = Setup { players: 2, opponent, deals: DEALS, stack_bb: 100.0, seed: SEED, blind: false };
|
||||
let blind = Setup { blind: true, ..read };
|
||||
(deal_samples(&blind).0, deal_samples(&read).0)
|
||||
}
|
||||
|
||||
// Die zwei Messungen spielen je 2x1000 echte Austeilungen (Minuten, release): nicht im schnellen
|
||||
// `cargo test`, nur auf Abruf mit `cargo test --release -- --ignored`. Die Zahlen stehen ohnehin
|
||||
// in `benchmarks/baseline.txt` (die Szenarien `... (blind)` gegen ihre read-given-Zwillinge).
|
||||
#[test]
|
||||
#[ignore = "spielt 2x1000 Austeilungen; auf Abruf: cargo test --release -- --ignored"]
|
||||
fn reading_the_fish_is_worth_a_clear_prize() {
|
||||
// Blind barrelt die Engine den Fisch zu viel (Populations-Prior) und laesst duenne Value liegen;
|
||||
// gelesen nicht. Der Preis ist gross und positiv. ~ +53,8 bb/100 bei diesem Seed.
|
||||
let (blind, read) = paired(Opponent::Reader(Style::Fish));
|
||||
let c = compare(&blind, &read).expect("vergleichbar");
|
||||
assert_ne!(c.verdict, Verdict::Worse, "{:+.1} ± {:.1} bb/100", c.delta_bb_per_100, c.ci95);
|
||||
assert!(c.delta_bb_per_100 > 40.0, "Preis nur {:+.1} bb/100", c.delta_bb_per_100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "spielt 2x1000 Austeilungen; auf Abruf: cargo test --release -- --ignored"]
|
||||
fn reading_the_calling_station_pays_and_never_costs() {
|
||||
// Die Station ueberbezahlt, also verdient die Engine auch blind gut; der Read bringt trotzdem
|
||||
// einen positiven Aufschlag und schadet nie. ~ +26,3 bb/100 bei diesem Seed.
|
||||
let (blind, read) = paired(Opponent::CallingStation);
|
||||
let c = compare(&blind, &read).expect("vergleichbar");
|
||||
assert_ne!(c.verdict, Verdict::Worse, "{:+.1} ± {:.1} bb/100", c.delta_bb_per_100, c.ci95);
|
||||
assert!(c.delta_bb_per_100 > 10.0, "Preis nur {:+.1} bb/100", c.delta_bb_per_100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_blind_scenarios_are_on_the_ladder_and_withhold_the_read() {
|
||||
// Die Messlatte traegt die zwei Blind-Szenarien, und nur die sind blind.
|
||||
let blind: Vec<_> = SCENARIOS.iter().filter(|s| s.setup.blind).map(|s| s.name).collect();
|
||||
assert_eq!(blind, ["heads-up fish (blind)", "heads-up calling station (blind)"]);
|
||||
assert_eq!(SCENARIOS.iter().filter(|s| !s.setup.blind).count(), 10);
|
||||
}
|
||||
@@ -15,7 +15,7 @@ use rechner::sim::session::{measure, measure_at, Measurement, Setup};
|
||||
use rechner::sim::table::{deal, play_hand, play_hand_at, Deal, HandSetup, TableCost};
|
||||
|
||||
fn setup(players: u8, opponent: Opponent, deals: u32) -> Setup {
|
||||
Setup { players, opponent, deals, stack_bb: 100.0, seed: 0x5EED_0001 }
|
||||
Setup { players, opponent, deals, stack_bb: 100.0, seed: 0x5EED_0001, blind: false }
|
||||
}
|
||||
|
||||
fn cards(text: &str) -> Vec<Card> {
|
||||
@@ -98,6 +98,7 @@ fn folder_in_the_small_blind_gives_the_big_blind_away() {
|
||||
opponent: Opponent::Folder,
|
||||
stack_bb: 100.0,
|
||||
seed: 1,
|
||||
blind: false,
|
||||
});
|
||||
assert_eq!(r.hero_net, 0.5);
|
||||
assert_eq!(r.hero_decisions, 0);
|
||||
@@ -113,6 +114,7 @@ fn aces_against_a_calling_station_win_the_showdown() {
|
||||
opponent: Opponent::CallingStation,
|
||||
stack_bb: 100.0,
|
||||
seed: 1,
|
||||
blind: false,
|
||||
});
|
||||
assert!(r.hero_net > 1.0, "aces won only {}", r.hero_net);
|
||||
assert!(r.hero_decisions >= 2);
|
||||
@@ -135,6 +137,7 @@ fn every_hand_conserves_chips_and_sends_only_valid_requests() {
|
||||
opponent,
|
||||
stack_bb: 100.0,
|
||||
seed: 5,
|
||||
blind: false,
|
||||
});
|
||||
assert!(r.chips_lost.abs() < 1e-6, "{opponent:?} {players}: {}", r.chips_lost);
|
||||
assert_eq!(r.invalid, 0, "{opponent:?} {players}");
|
||||
@@ -204,7 +207,7 @@ fn long_run_heads_up_and_six_max() {
|
||||
// -- Rake und Ante --------------------------------------------------------------------------
|
||||
|
||||
fn at_measured_table(d: &Deal, hero_seat: u8, opponent: Opponent) -> rechner::sim::table::HandResult {
|
||||
play_hand_at(&HandSetup { deal: d, hero_seat, opponent, stack_bb: 100.0, seed: 1 }, TableCost::MEASURED)
|
||||
play_hand_at(&HandSetup { deal: d, hero_seat, opponent, stack_bb: 100.0, seed: 1, blind: false }, TableCost::MEASURED)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -220,7 +223,7 @@ fn a_hand_that_ends_before_the_flop_pays_antes_but_no_rake() {
|
||||
#[test]
|
||||
fn a_showdown_pays_rake_and_the_chips_balance() {
|
||||
let d = fixed_deal(&["As Ah", "7c 2d"], "Kd Qc 9s 4h 3c");
|
||||
let free = play_hand(&HandSetup { deal: &d, hero_seat: 1, opponent: Opponent::CallingStation, stack_bb: 100.0, seed: 1 });
|
||||
let free = play_hand(&HandSetup { deal: &d, hero_seat: 1, opponent: Opponent::CallingStation, stack_bb: 100.0, seed: 1, blind: false });
|
||||
let raked = at_measured_table(&d, 1, Opponent::CallingStation);
|
||||
assert!(raked.rake > 0.0 && raked.rake <= 1.0, "{}", raked.rake);
|
||||
assert!(free.hero_net > 0.0);
|
||||
@@ -234,7 +237,7 @@ fn six_handed_random_hands_balance_with_the_rake_within_the_cap() {
|
||||
let (d, _) = deal(6, Rng::seeded(seed));
|
||||
for hero_seat in 1..=6u8 {
|
||||
let r = play_hand_at(
|
||||
&HandSetup { deal: &d, hero_seat, opponent: Opponent::RandomLegal, stack_bb: 100.0, seed },
|
||||
&HandSetup { deal: &d, hero_seat, opponent: Opponent::RandomLegal, stack_bb: 100.0, seed, blind: false },
|
||||
TableCost::MEASURED,
|
||||
);
|
||||
assert!(r.chips_lost.abs() < 1e-6, "{}", r.chips_lost);
|
||||
|
||||
Reference in New Issue
Block a user