D4 Entscheidungs-Audit automatisch: Turn+River, Preflop/Flop-Preise, Lauf- und Wochenbericht, Cockpit /audit, Haken
- engine::audit_turn: Turn-Entscheidungen im Turn+River-Spiel (E3-Löser) nachgerechnet, EV je Aktion fuer die echte Hand (TrSolver::hand_action_values), Gegner-Range entlang der Linie - engine::audit_allin: Preflop gegen All-in (Equity gegen Nash-Push-Range vs Preis), Push/Fold first-in <= 25 bb (Nash-Spiel der Charts), Flop gegen All-in (exakte Equity vs Preis) - bin/audit: Feld method/note, --turn-iters/--turn-combos/--turn-cards - lesen/audit_lauf.py: exakte Spots aus dem Schatten-Log, Cache je Lauf, Bericht je Lauf (Street, Messlatte, Engine-Teil, Top 10), Wochensumme, Fixture-Vorschlaege - sicht/audit_seite.py + Route: /audit, /api/audit, /api/audit/laeufe, /api/audit/woche - betrieb/audit_haken.py + docs/notizen/D4-audit-haken.patch (runner.py, 3 Zeilen) - tests/audit_lauf_spec.py 12/12; cargo test engine::audit 14/14 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,3 +18,6 @@ daten/grundstrategie/
|
||||
|
||||
# Engine-Roentgen: Kern-Kopie und Nachspiel-Cache (lesen/roentgen.py), aus dem Lauf reproduzierbar
|
||||
archiv/roentgen/
|
||||
|
||||
# Entscheidungs-Audit D4: Berichte, Cache, Bin-Kopie (lesen/audit_lauf.py), je Baum aus dem Lauf erzeugt
|
||||
archiv/audit/
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Haken nach jedem Läuferlauf: startet den Entscheidungs-Audit (Plan D4, lesen/audit_lauf.py) für
|
||||
DIESEN Lauf abgekoppelt im Hintergrund, Priorität Idle. Der Läufer wartet nie darauf und kein Fehler
|
||||
des Audits erreicht ihn.
|
||||
|
||||
Eingebaut in `betrieb/runner.py`, `live()`, im `finally` nach dem Freigeben der Sperre:
|
||||
|
||||
audit_haken.anstossen()
|
||||
|
||||
Schalter `AUDIT_NACH_LAUF=0` schaltet ihn ab. Der Audit schreibt nach archiv/audit/ (lauf-<pid>.md,
|
||||
woche-<JJJJ>-W<KW>.md) und tests/live_fixture/vorschlag/; Fehler nach archiv/audit/fehler.log.
|
||||
Nur im Klick-Betrieb sinnvoll (der Schatten klickt nicht, seine Anfragen zählen als nicht geklickt).
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
BAUM = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SKRIPT = os.path.join(BAUM, "lesen", "audit_lauf.py")
|
||||
IDLE_PRIORITY_CLASS = 0x00000040
|
||||
DETACHED_PROCESS = 0x00000008
|
||||
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
|
||||
|
||||
def befehl(pid, wurzel=BAUM, python=None):
|
||||
"""Die Kommandozeile des Audits für den Lauf `pid`."""
|
||||
return [python or sys.executable, SKRIPT, "--nach-lauf", "--pid", str(pid), "--wurzel", wurzel]
|
||||
|
||||
|
||||
def anstossen(pid=None, wurzel=BAUM, starten=None):
|
||||
"""Startet den Audit für `pid` (Vorgabe: dieser Prozess = der Läufer) und kehrt sofort zurück.
|
||||
-> der gestartete Prozess, oder None (abgeschaltet oder Start gescheitert). Wirft nie."""
|
||||
try:
|
||||
if os.environ.get("AUDIT_NACH_LAUF", "1") == "0":
|
||||
return None
|
||||
pid = os.getpid() if pid is None else pid
|
||||
kw = {"cwd": wurzel, "stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL,
|
||||
"stderr": subprocess.DEVNULL, "close_fds": True}
|
||||
if sys.platform == "win32":
|
||||
kw["creationflags"] = IDLE_PRIORITY_CLASS | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW
|
||||
else:
|
||||
kw["start_new_session"] = True
|
||||
kw["preexec_fn"] = lambda: os.nice(19)
|
||||
return (starten or subprocess.Popen)(befehl(pid, wurzel), **kw)
|
||||
except Exception: # noqa: BLE001 - ein Audit darf das Ende des Läufers nie stören
|
||||
return None
|
||||
@@ -0,0 +1,21 @@
|
||||
diff --git a/betrieb/runner.py b/betrieb/runner.py
|
||||
index b6a0775..3879187 100644
|
||||
--- a/betrieb/runner.py
|
||||
+++ b/betrieb/runner.py
|
||||
@@ -104,6 +104,7 @@ import tischzahlen
|
||||
import dialog
|
||||
import ergebnis
|
||||
import allin_ev
|
||||
+import audit_haken # D4: Entscheidungs-Audit nach jedem Lauf (lesen/audit_lauf.py)
|
||||
import statistik
|
||||
import strom
|
||||
import tara_ereignisse
|
||||
@@ -4093,6 +4094,8 @@ def live(klicken=False):
|
||||
ZAEHLBUCH = None
|
||||
spot_from_log.HAND_FERTIG = None
|
||||
sperre.freigeben(SPERRE)
|
||||
+ if klicken: # D4: Audit dieses Laufs, abgekoppelt, Priorität Idle, wirft nie
|
||||
+ audit_haken.anstossen()
|
||||
|
||||
|
||||
lauf = live # der Name der Schleife in den Tests (tests/laeufer_sitzen_spec.py)
|
||||
@@ -0,0 +1,609 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Entscheidungs-Audit je Läuferlauf (Plan D4), automatisch: jede echte Entscheidung des Laufs wird
|
||||
nachgerechnet, EV-Verlust je Entscheidung, die teuersten Spots mit Hand, Brett und Grund, dazu eine
|
||||
Wochensumme und Fixture-Vorschläge für neue teure Spots.
|
||||
|
||||
Woher die Spots kommen. Der Schatten-Log des Läufers (`betrieb/scratch/shadow*.jsonl`) führt je
|
||||
Entscheidung die volle Anfrage an den Kern (`anfrage`: Karten, Brett, Pot, Stände, Verlauf, Profile)
|
||||
und seine Antwort (`antwort`). Das ist der Spot ohne jede Rekonstruktion. Gezählt wird je Entscheidung
|
||||
(`zug`-Schlüssel) die letzte geklickte Anfrage; Enthaltungen der Übersetzung und nie geklickte Anfragen
|
||||
zählen als ausgelassen.
|
||||
|
||||
Was gerechnet wird (Rust-Bin `src/bin/audit.rs`, ein Prozess, ein Thread, Priorität Idle):
|
||||
RIVER river_game das ganze River-Spiel (CFR+), heads-up
|
||||
TURN turn_river_game Turn+River über echte Combos (E3-Löser), heads-up
|
||||
PREFLOP jam_preis gegen ein All-in: Equity gegen die Nash-Push-Range des Jammers vs. Preis
|
||||
push_fold first-in mit kurzem Stack (<= 25 bb): Nash-Push/Fold-Spiel der Charts
|
||||
FLOP allin_equity gegen ein All-in: exakte Equity gegen die Range vs. Preis
|
||||
Alles andere (Multiway, Preflop ohne All-in bei tiefen Ständen, Flop ohne All-in) wird mit Grund
|
||||
ausgelassen und gezählt. Verlust = EV(beste Aktion) - EV(gespielte Aktion) gegen den
|
||||
Gleichgewichts-Gegner der angenommenen Ranges, in BB. Er misst Entscheidungen, nicht Ergebnisse.
|
||||
|
||||
Ablage (unter --ziel, Vorgabe = --wurzel):
|
||||
archiv/audit/lauf-<pid>.json / .md Bericht je Lauf (Summen + die teuersten Spots)
|
||||
archiv/audit/woche-<JJJJ>-W<KW>.json/.md Wochensumme aus allen Laufberichten der Woche
|
||||
archiv/audit/cache/ Ergebnisse je Anfrage (ein späterer Blick rechnet nur Neues)
|
||||
archiv/audit/kern/pokerbench-audit-lauf.exe Kopie der Bin (sperrt nie einen Bau)
|
||||
tests/live_fixture/vorschlag/audit-<datum>.jsonl neue teure Spots als Fixture-Vorschlag
|
||||
|
||||
python3 lesen/audit_lauf.py letzter Lauf
|
||||
python3 lesen/audit_lauf.py --pid 43432
|
||||
python3 lesen/audit_lauf.py --tag 2026-11-14 jeder Lauf des Tages, dann die Wochensumme
|
||||
python3 lesen/audit_lauf.py --woche nur die Wochensumme (aus den Laufberichten)
|
||||
python3 lesen/audit_lauf.py --liste
|
||||
Haken nach dem Lauf: `betrieb/audit_haken.py` (startet dies abgekoppelt, Priorität Idle).
|
||||
Spezifikation: tests/audit_lauf_spec.py. Reine Funktionen bis auf Laden, `rechne` und Schreiben.
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import datetime
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
_HIER = os.path.dirname(os.path.abspath(__file__))
|
||||
if _HIER not in sys.path:
|
||||
sys.path.insert(0, _HIER)
|
||||
import roentgen # noqa: E402 Schatten-Log, Läufe, wer entschied
|
||||
|
||||
BAUM = os.path.dirname(_HIER)
|
||||
STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER")
|
||||
TOP = 10 # teuerste Spots im Bericht
|
||||
TOP_GESPEICHERT = 25 # je Laufbericht gespeichert (die Woche wählt daraus ihre Top 10)
|
||||
SCHWELLE_FIXTURE_BB = 3.0 # ab diesem Verlust wird ein neuer Spot Fixture-Vorschlag
|
||||
IDLE = 0x00000040
|
||||
BIN_KOPIE = "pokerbench-audit-lauf" + (".exe" if sys.platform == "win32" else "")
|
||||
OPTS_STANDARD = {"iters": 5000, "turn_iters": 200, "turn_combos": 200, "turn_cards": 10}
|
||||
METHODE_NAME = {
|
||||
"river_game": "River-Spiel", "turn_river_game": "Turn+River-Spiel", "jam_preis": "Preis gegen Jam",
|
||||
"push_fold": "Push/Fold (Nash)", "allin_equity": "Preis gegen All-in",
|
||||
}
|
||||
KARTE = {"ACE": "A", "KING": "K", "QUEEN": "Q", "JACK": "J", "TEN": "T", "NINE": "9", "EIGHT": "8",
|
||||
"SEVEN": "7", "SIX": "6", "FIVE": "5", "FOUR": "4", "THREE": "3", "TWO": "2"}
|
||||
FARBE = {"SPADES": "s", "HEARTS": "h", "DIAMONDS": "d", "CLUBS": "c"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Spots aus dem Schatten-Log
|
||||
|
||||
def karte(c):
|
||||
if isinstance(c, dict):
|
||||
return KARTE.get(c.get("rank"), "?") + FARBE.get(c.get("suit"), "?")
|
||||
return str(c)
|
||||
|
||||
|
||||
def brett(anfrage):
|
||||
b = anfrage.get("board") or {}
|
||||
if isinstance(b, list):
|
||||
return [karte(c) for c in b]
|
||||
return [karte(c) for s in ("FLOP", "TURN", "RIVER") for c in b.get(s) or ()]
|
||||
|
||||
|
||||
def hand_id(e):
|
||||
teile = str(e.get("zug") or "").split("|")
|
||||
if len(teile) > 1 and teile[1]:
|
||||
return teile[1]
|
||||
k = str(e.get("kurz") or "").split()
|
||||
return k[0] if k else None
|
||||
|
||||
|
||||
def genommen(anfrage, antwort):
|
||||
"""Die gespielte Aktion im Format der Bin, oder None (unbekannte Aktion)."""
|
||||
a = (antwort or {}).get("action")
|
||||
if a in ("FOLD", "CHECK", "CALL"):
|
||||
return {"action": a}
|
||||
if a in ("RAISE", "BET", "ALL_IN"):
|
||||
x = (antwort or {}).get("size")
|
||||
if not isinstance(x, (int, float)) or x <= 0:
|
||||
x = anfrage.get("maxRaiseTo")
|
||||
if not isinstance(x, (int, float)) or x <= 0:
|
||||
return None
|
||||
return {"action": a, "amount": float(x)}
|
||||
return None
|
||||
|
||||
|
||||
def entscheidungen(schatten_lauf):
|
||||
"""(liste, ausgelassen): je Entscheidung (`zug`) die letzte geklickte Anfrage.
|
||||
liste: [{e, anfrage, taken}]; ausgelassen: Counter Grund -> Anzahl."""
|
||||
je, reihenfolge, aus = {}, [], collections.Counter()
|
||||
for e in schatten_lauf:
|
||||
if "anfrage" not in e:
|
||||
continue
|
||||
a = roentgen._als_dict(e.get("anfrage"))
|
||||
if not a:
|
||||
aus["Anfrage unlesbar"] += 1
|
||||
continue
|
||||
if a.get("legalActions") == [] and a.get("_unklar"):
|
||||
aus["Enthaltung (Übersetzung)"] += 1
|
||||
continue
|
||||
schl = e.get("zug") or json.dumps(a, sort_keys=True)
|
||||
if schl not in je:
|
||||
reihenfolge.append(schl)
|
||||
je[schl] = []
|
||||
je[schl].append((e, a))
|
||||
out = []
|
||||
for schl in reihenfolge:
|
||||
paare = je[schl]
|
||||
geklickt = [p for p in paare if p[0].get("geklickt")]
|
||||
if not geklickt:
|
||||
aus["nicht geklickt"] += 1
|
||||
continue
|
||||
e, a = geklickt[-1]
|
||||
t = genommen(a, roentgen._als_dict(e.get("antwort")) or {})
|
||||
if t is None:
|
||||
aus["Aktion unbekannt"] += 1
|
||||
continue
|
||||
out.append({"e": e, "anfrage": a, "taken": t})
|
||||
return out, aus
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Rechnen (Bin, Cache)
|
||||
|
||||
def bin_suchen(wurzel, ziel):
|
||||
"""Die neueste gebaute audit-Bin (AUDIT_BIN gewinnt)."""
|
||||
if os.environ.get("AUDIT_BIN"):
|
||||
return os.environ["AUDIT_BIN"]
|
||||
name = "audit.exe" if sys.platform == "win32" else "audit"
|
||||
kandidaten = []
|
||||
for w in dict.fromkeys((ziel, wurzel, BAUM)):
|
||||
for rel in ("target/release", "target_mess/release"):
|
||||
p = os.path.join(w, rel, name)
|
||||
if os.path.exists(p):
|
||||
kandidaten.append(p)
|
||||
return max(kandidaten, key=os.path.getmtime) if kandidaten else None
|
||||
|
||||
|
||||
def bin_kopie(quelle, ordner):
|
||||
"""Kopie nach ordner/pokerbench-audit-lauf(.exe), wenn sie sich geändert hat."""
|
||||
os.makedirs(ordner, exist_ok=True)
|
||||
ziel = os.path.join(ordner, BIN_KOPIE)
|
||||
q = os.stat(quelle)
|
||||
try:
|
||||
z = os.stat(ziel)
|
||||
if z.st_size == q.st_size and abs(z.st_mtime - q.st_mtime) < 1:
|
||||
return ziel
|
||||
except OSError:
|
||||
pass
|
||||
shutil.copy2(quelle, ziel)
|
||||
return ziel
|
||||
|
||||
|
||||
def bin_id(pfad):
|
||||
st = os.stat(pfad)
|
||||
return hashlib.sha1(f"{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:8]
|
||||
|
||||
|
||||
def schluessel(anfrage, taken, opts):
|
||||
roh = json.dumps([anfrage, taken, opts], sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha1(roh.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def bin_aufruf(binary, opts, env=None):
|
||||
"""rechner(zeilen) -> ergebnisse: ein Prozess, Priorität Idle. zeilen: Drahtformat + taken."""
|
||||
def rechner(zeilen):
|
||||
if not zeilen:
|
||||
return []
|
||||
umgebung = {k: v for k, v in os.environ.items() if k not in roentgen.BEKANNTE_SCHALTER}
|
||||
umgebung.update(env or {})
|
||||
extra = {"creationflags": IDLE} if sys.platform == "win32" else {"preexec_fn": lambda: os.nice(19)}
|
||||
args = [binary, "--iters", str(opts["iters"]), "--turn-iters", str(opts["turn_iters"]),
|
||||
"--turn-combos", str(opts["turn_combos"]), "--turn-cards", str(opts["turn_cards"])]
|
||||
eingabe = "".join(json.dumps(dict(z, id=i), ensure_ascii=False) + "\n" for i, z in enumerate(zeilen))
|
||||
r = subprocess.run(args, input=eingabe.encode("utf-8"), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
env=umgebung, **extra)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(f"audit-Bin scheiterte: {r.stderr.decode('utf-8', 'replace')[:300]}")
|
||||
out = [json.loads(x) for x in r.stdout.decode("utf-8").splitlines() if x.strip()]
|
||||
if len(out) != len(zeilen):
|
||||
raise RuntimeError(f"Bin lieferte {len(out)} Zeilen für {len(zeilen)} Spots")
|
||||
return out
|
||||
return rechner
|
||||
|
||||
|
||||
def rechne(entsch, rechner, opts, cache, paket=50, fortschritt=None):
|
||||
"""Ergebnis je Entscheidung (gleiche Reihenfolge); nur Neues geht an die Bin, in Paketen
|
||||
(ein Abbruch verliert höchstens ein Paket). cache: dict schluessel -> ergebnis (wird ergänzt)."""
|
||||
schl = [schluessel(d["anfrage"], d["taken"], opts) for d in entsch]
|
||||
offen = [i for i, s in enumerate(schl) if s not in cache]
|
||||
for k in range(0, len(offen), paket):
|
||||
teil = offen[k:k + paket]
|
||||
zeilen = [{**{x: y for x, y in entsch[i]["anfrage"].items() if not x.startswith("_")},
|
||||
"taken": entsch[i]["taken"]} for i in teil]
|
||||
for i, er in zip(teil, rechner(zeilen)):
|
||||
er.pop("id", None)
|
||||
cache[schl[i]] = er
|
||||
if fortschritt:
|
||||
fortschritt(min(k + paket, len(offen)), len(offen))
|
||||
return [cache[s] for s in schl]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Auswerten
|
||||
|
||||
def _aktion_text(act):
|
||||
if not act:
|
||||
return "?"
|
||||
n = act.get("act", "?")
|
||||
return f"{n} {act['to']:.2f}" if "to" in act else n
|
||||
|
||||
|
||||
def datensatz(d, er, haende_by_id):
|
||||
"""Ein Bericht-Datensatz je Entscheidung."""
|
||||
e, a = d["e"], d["anfrage"]
|
||||
antwort = roentgen._als_dict(e.get("antwort")) or {}
|
||||
street = a.get("street")
|
||||
bb = float(a.get("bigBlind") or 0) or 1.0
|
||||
hid = hand_id(e)
|
||||
h = haende_by_id.get(hid)
|
||||
erg = None
|
||||
if h is not None:
|
||||
import liveabgleich
|
||||
erg = liveabgleich.netto_bb(h)
|
||||
ok = er.get("status") == "ok"
|
||||
acts = er.get("acts") or []
|
||||
best = max(acts, key=lambda x: x.get("ev", float("-inf"))) if acts else None
|
||||
gespielt = acts[er["taken"]] if ok and 0 <= er.get("taken", -1) < len(acts) else None
|
||||
t = d["taken"]
|
||||
return {
|
||||
"zeit": e.get("zeit"), "raum": e.get("raum"), "hand": hid, "street": street,
|
||||
"karten": " ".join(karte(c) for c in a.get("heroCards") or ()), "brett": " ".join(brett(a)),
|
||||
"pot_bb": float(a.get("pot") or 0) / bb, "to_call_bb": float(a.get("toCall") or 0) / bb,
|
||||
"gespielt": t["action"] + (f" {t['amount']:.2f}" if "amount" in t else ""),
|
||||
"grund": antwort.get("reason") or "", "wer": roentgen.klasse(street, antwort.get("reason")),
|
||||
"wer_name": roentgen.KLASSEN_NAME.get(roentgen.klasse(street, antwort.get("reason")), "?"),
|
||||
"status": er.get("status"), "auslass": None if ok else (er.get("reason") or "?"),
|
||||
"verlust_bb": float(er.get("loss_bb") or 0.0) if ok else None,
|
||||
"methode": er.get("method") or ("river_game" if ok and street == "RIVER" else None),
|
||||
"quelle": er.get("source"), "notiz": er.get("note") or "",
|
||||
"beste": _aktion_text(best), "gespielt_als": _aktion_text(gespielt),
|
||||
"loesung": ", ".join(f"{_aktion_text(x)} {100 * x.get('p', 0):.0f}%" for x in acts),
|
||||
"ergebnis_bb": erg, "_anfrage": a,
|
||||
}
|
||||
|
||||
|
||||
def _summe():
|
||||
return {"n": 0, "bewertet": 0, "verlust_bb": 0.0, "gross": 0}
|
||||
|
||||
|
||||
def _addiere(s, r):
|
||||
s["n"] += 1
|
||||
if r["verlust_bb"] is not None:
|
||||
s["bewertet"] += 1
|
||||
s["verlust_bb"] += r["verlust_bb"]
|
||||
s["gross"] += r["verlust_bb"] > 0.5
|
||||
|
||||
|
||||
def auswerten(daten, lauf, ausgelassen_vorab, haende_n, top_n=TOP_GESPEICHERT):
|
||||
"""Laufbericht als dict (JSON-fähig, ohne die volle Liste)."""
|
||||
je_street = {s: _summe() for s in STREETS + ("GESAMT",)}
|
||||
je_methode, je_wer = collections.defaultdict(_summe), collections.defaultdict(_summe)
|
||||
auslass = collections.Counter(ausgelassen_vorab)
|
||||
auslass_street = collections.defaultdict(collections.Counter)
|
||||
for r in daten:
|
||||
s = r["street"] if r["street"] in STREETS else "GESAMT"
|
||||
_addiere(je_street[s], r)
|
||||
if s != "GESAMT":
|
||||
_addiere(je_street["GESAMT"], r)
|
||||
if r["verlust_bb"] is not None:
|
||||
_addiere(je_methode[r["methode"] or "?"], r)
|
||||
_addiere(je_wer[r["wer"]], r)
|
||||
else:
|
||||
auslass_street[r["street"]][r["auslass"]] += 1
|
||||
bewertet = [r for r in daten if r["verlust_bb"] is not None]
|
||||
top = sorted(bewertet, key=lambda r: -r["verlust_bb"])[:top_n]
|
||||
return {
|
||||
"lauf": lauf, "erstellt": time.strftime("%Y-%m-%d %H:%M:%S"), "haende": haende_n,
|
||||
"entscheidungen": len(daten), "vorab_ausgelassen": dict(auslass),
|
||||
"streets": je_street, "methoden": dict(je_methode), "wer": dict(je_wer),
|
||||
"auslass_je_street": {s: dict(c.most_common()) for s, c in auslass_street.items()},
|
||||
"top": [{k: v for k, v in r.items() if not k.startswith("_")} for r in top],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Fixture-Vorschläge
|
||||
|
||||
def fixture_haende(ordner):
|
||||
"""(hand, street) aller Spots in tests/live_fixture (auch vorschlag/)."""
|
||||
bekannt = set()
|
||||
for p in glob.glob(os.path.join(ordner, "**", "*.jsonl"), recursive=True):
|
||||
for d in roentgen.jsonl(p):
|
||||
s = (d.get("spot") or {}).get("street") if isinstance(d.get("spot"), dict) else None
|
||||
bekannt.add((str(d.get("hand")), s))
|
||||
return bekannt
|
||||
|
||||
|
||||
def fixture_vorschlaege(daten, bekannt, schwelle=SCHWELLE_FIXTURE_BB):
|
||||
"""Neue teure Spots als Zeilen im Format der Live-Fixture (hand, art, live, live_grund,
|
||||
ergebnis_bb, spot) plus `audit` (Verlust, beste Aktion, Messlatte)."""
|
||||
aus = []
|
||||
for r in sorted(daten, key=lambda r: -(r["verlust_bb"] or 0)):
|
||||
if r["verlust_bb"] is None or r["verlust_bb"] < schwelle:
|
||||
break
|
||||
if (str(r["hand"]), r["street"]) in bekannt:
|
||||
continue
|
||||
bekannt.add((str(r["hand"]), r["street"]))
|
||||
aus.append({
|
||||
"hand": r["hand"], "art": f"audit_{(r['street'] or '').lower()}_{r['wer']}",
|
||||
"live": r["gespielt"].split()[0], "live_grund": r["grund"], "ergebnis_bb": r["ergebnis_bb"],
|
||||
"audit": {"verlust_bb": round(r["verlust_bb"], 3), "beste": r["beste"], "methode": r["methode"],
|
||||
"quelle": r["quelle"], "notiz": r["notiz"], "zeit": r["zeit"]},
|
||||
"spot": r["_anfrage"],
|
||||
})
|
||||
return aus
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Woche
|
||||
|
||||
def iso_woche(zeit):
|
||||
d = datetime.datetime.strptime(zeit[:10], "%Y-%m-%d").date()
|
||||
j, w, _ = d.isocalendar()
|
||||
return f"{j}-W{w:02d}"
|
||||
|
||||
|
||||
def woche_summe(berichte, woche):
|
||||
"""Summe der Laufberichte einer ISO-Woche (Top 10 aus den gespeicherten Top-Spots aller Läufe)."""
|
||||
drin = [b for b in berichte if b.get("lauf", {}).get("von") and iso_woche(b["lauf"]["von"]) == woche]
|
||||
aus = {"woche": woche, "laeufe": [b["lauf"] for b in drin], "haende": sum(b.get("haende") or 0 for b in drin),
|
||||
"entscheidungen": sum(b.get("entscheidungen") or 0 for b in drin),
|
||||
"streets": {s: _summe() for s in STREETS + ("GESAMT",)}, "methoden": {}, "wer": {},
|
||||
"vorab_ausgelassen": collections.Counter(), "auslass_je_street": {}, "top": []}
|
||||
for b in drin:
|
||||
for feld in ("streets", "methoden", "wer"):
|
||||
for k, v in (b.get(feld) or {}).items():
|
||||
z = aus[feld].setdefault(k, _summe())
|
||||
for x in z:
|
||||
z[x] += v.get(x, 0)
|
||||
aus["vorab_ausgelassen"].update(b.get("vorab_ausgelassen") or {})
|
||||
for s, c in (b.get("auslass_je_street") or {}).items():
|
||||
z = aus["auslass_je_street"].setdefault(s, collections.Counter())
|
||||
z.update(c)
|
||||
aus["top"].extend(b.get("top") or [])
|
||||
aus["top"] = sorted(aus["top"], key=lambda r: -r["verlust_bb"])[:TOP_GESPEICHERT]
|
||||
aus["vorab_ausgelassen"] = dict(aus["vorab_ausgelassen"])
|
||||
aus["auslass_je_street"] = {s: dict(c.most_common()) for s, c in aus["auslass_je_street"].items()}
|
||||
return aus
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Text
|
||||
|
||||
def _zeile_summe(name, s, haende):
|
||||
if not s["n"]:
|
||||
return f"| {name} | 0 | 0 | - | - | - | - |"
|
||||
m = s["verlust_bb"] / s["bewertet"] if s["bewertet"] else 0.0
|
||||
h = f"{100 * s['verlust_bb'] / haende:.2f}" if haende else "-"
|
||||
g = f"{100 * s['gross'] / s['bewertet']:.0f} %" if s["bewertet"] else "-"
|
||||
return f"| {name} | {s['n']} | {s['bewertet']} | {s['verlust_bb']:.1f} | {m:.3f} | {g} | {h} |"
|
||||
|
||||
|
||||
def markdown(b, titel=None):
|
||||
"""Bericht (Lauf oder Woche) als Markdown."""
|
||||
L = []
|
||||
if "woche" in b:
|
||||
L.append(f"# {titel or 'Entscheidungs-Audit (D4)'}: Woche {b['woche']}\n")
|
||||
L.append(f"{len(b['laeufe'])} Läufe, {b['entscheidungen']} Entscheidungen, {b['haende']} Hände.\n")
|
||||
else:
|
||||
lf = b["lauf"]
|
||||
L.append(f"# {titel or 'Entscheidungs-Audit (D4)'}: Lauf pid {lf.get('pid')}\n")
|
||||
L.append(f"{lf.get('von')} bis {lf.get('bis')}; {b['entscheidungen']} Entscheidungen, {b['haende']} Hände; "
|
||||
f"erstellt {b.get('erstellt')}.\n")
|
||||
L.append("Verlust = EV(beste Aktion) - EV(gespielte Aktion) gegen den Gleichgewichts-Gegner der angenommenen "
|
||||
"Ranges, in BB. Er bewertet Entscheidungen, nicht Ergebnisse.\n")
|
||||
L.append("## Verlust je Street\n")
|
||||
L.append("| Street | Entscheidungen | bewertet | Verlust (bb) | je bewertete (bb) | Anteil > 0,5 bb | bb/100 Hände |")
|
||||
L.append("|---|---:|---:|---:|---:|---:|---:|")
|
||||
for s in STREETS + ("GESAMT",):
|
||||
L.append(_zeile_summe(s, b["streets"][s], b["haende"]))
|
||||
L.append("")
|
||||
if b.get("vorab_ausgelassen"):
|
||||
L.append("Vorab ausgelassen: " + "; ".join(f"{k} ({v})" for k, v in sorted(b["vorab_ausgelassen"].items(), key=lambda kv: -kv[1])) + ".\n")
|
||||
for s in STREETS:
|
||||
c = (b.get("auslass_je_street") or {}).get(s)
|
||||
if c:
|
||||
L.append(f"- {s} nicht bewertet: " + "; ".join(f"{k} ({v})" for k, v in list(c.items())[:5]) + ".")
|
||||
L.append("")
|
||||
L.append("## Verlust je Messlatte\n")
|
||||
L.append("| Messlatte | Entscheidungen | bewertet | Verlust (bb) | je bewertete (bb) | Anteil > 0,5 bb | bb/100 Hände |")
|
||||
L.append("|---|---:|---:|---:|---:|---:|---:|")
|
||||
for k, s in sorted(b["methoden"].items(), key=lambda kv: -kv[1]["verlust_bb"]):
|
||||
L.append(_zeile_summe(METHODE_NAME.get(k, k), s, b["haende"]))
|
||||
L.append("")
|
||||
L.append("## Verlust je Engine-Teil (wer entschied)\n")
|
||||
L.append("| Engine-Teil | Entscheidungen | bewertet | Verlust (bb) | je bewertete (bb) | Anteil > 0,5 bb | bb/100 Hände |")
|
||||
L.append("|---|---:|---:|---:|---:|---:|---:|")
|
||||
for k, s in sorted(b["wer"].items(), key=lambda kv: -kv[1]["verlust_bb"]):
|
||||
L.append(_zeile_summe(roentgen.KLASSEN_NAME.get(k, k), s, b["haende"]))
|
||||
L.append("")
|
||||
L.append(f"## Die {TOP} teuersten Entscheidungen\n")
|
||||
L.append("| # | Hand | Zeit | Street | Karten / Brett | Pot / toCall (bb) | gespielt | besser | Verlust (bb) | Hand-Ergebnis (bb) | Engine-Teil | Grund |")
|
||||
L.append("|---:|---|---|---|---|---|---|---|---:|---:|---|---|")
|
||||
for i, r in enumerate(b["top"][:TOP], 1):
|
||||
erg = "-" if r.get("ergebnis_bb") is None else f"{r['ergebnis_bb']:+.1f}"
|
||||
L.append(f"| {i} | {r['hand']} | {r['zeit']} | {r['street']} | {r['karten']} / {r['brett'] or '-'} | "
|
||||
f"{r['pot_bb']:.1f} / {r['to_call_bb']:.1f} | {r['gespielt_als']} | {r['beste']} | {r['verlust_bb']:.2f} | {erg} | "
|
||||
f"{roentgen.KLASSEN_NAME.get(r['wer'], r['wer'])} | {(r['grund'] or '')[:80].replace('|', '/')} |")
|
||||
L.append("")
|
||||
if b["top"]:
|
||||
L.append("Messlatte und Annahme je Spot (gleiche Reihenfolge): " + "; ".join(
|
||||
f"{i}. {METHODE_NAME.get(r['methode'], r['methode'])}, {r.get('quelle') or '-'}" + (f" ({r['notiz']})" if r.get("notiz") else "")
|
||||
for i, r in enumerate(b["top"][:TOP], 1)) + ".\n")
|
||||
if b.get("fixture"):
|
||||
L.append(f"Fixture-Vorschläge: {b['fixture']['neu']} neue Spots ab {b['fixture']['schwelle']} bb -> {b['fixture']['datei']}.\n")
|
||||
L.append("Lesart: (1) Gemessen gegen den Gleichgewichts-Gegner: ein bewusstes Ausnutzen eines Reads erscheint als "
|
||||
"Verlust. (2) Ranges 'modell' kennen die Linie davor nicht; belastbar sind Calls mit Quelle 'blueprint'. "
|
||||
"(3) Preflop- und Flop-Zahlen sind reine Preis-Rechnungen (All-in, Push/Fold), kein Löser über Linien. "
|
||||
"(4) Kleine Verluste (< 0,05 bb) liegen im Rauschen des Lösers.\n")
|
||||
return "\n".join(L)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Ablauf mit Platte
|
||||
|
||||
def _json_laden(pfad):
|
||||
try:
|
||||
with open(pfad, encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def _schreiben(pfad, inhalt):
|
||||
os.makedirs(os.path.dirname(pfad), exist_ok=True)
|
||||
tmp = pfad + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
||||
if isinstance(inhalt, str):
|
||||
f.write(inhalt)
|
||||
else:
|
||||
json.dump(inhalt, f, ensure_ascii=False, indent=1, default=str)
|
||||
os.replace(tmp, pfad)
|
||||
|
||||
|
||||
def ordner(ziel):
|
||||
return os.path.join(ziel, "archiv", "audit")
|
||||
|
||||
|
||||
def lauf_bericht(wurzel, ziel=None, pid=None, start=None, opts=None, d=None, fixtures=True,
|
||||
schwelle=SCHWELLE_FIXTURE_BB, binary=None, still=False):
|
||||
"""Rechnet einen Lauf, schreibt lauf-<pid>.json/.md und Fixture-Vorschläge. -> Bericht (dict)."""
|
||||
ziel = ziel or wurzel
|
||||
opts = dict(OPTS_STANDARD, **(opts or {}))
|
||||
d = d or roentgen.daten(wurzel)
|
||||
lauf = roentgen.waehle(roentgen.laeufe(d["schatten"]), pid=pid, start=start)
|
||||
if lauf is None:
|
||||
return {"fehler": "kein Lauf mit Entscheidungen im Schatten-Log"}
|
||||
von, bis = lauf["von"], lauf["bis"]
|
||||
schatten_lauf = [e for e in d["schatten"] if e.get("pid") == lauf["pid"]
|
||||
and isinstance(e.get("zeit"), str) and von <= e["zeit"] <= bis]
|
||||
entsch, aus = entscheidungen(schatten_lauf)
|
||||
quelle = binary or bin_suchen(wurzel, ziel)
|
||||
if not quelle:
|
||||
return {"fehler": "audit-Bin nicht gebaut: cargo build --release -j 4 --bin audit"}
|
||||
kopie = bin_kopie(quelle, os.path.join(ordner(ziel), "kern"))
|
||||
schalter = roentgen.lies_schalter(os.path.join(wurzel, "betrieb", "kern_schalter.txt"))
|
||||
env = {k: v for k, v in schalter.items() if k == "GRUNDSTRATEGIE"}
|
||||
cpfad = os.path.join(ordner(ziel), "cache", f"lauf-{lauf['pid']}-{bin_id(quelle)}.json")
|
||||
cache = _json_laden(cpfad)
|
||||
vorher = len(cache)
|
||||
|
||||
def fortschritt(k, n):
|
||||
if not still:
|
||||
print(f" {k}/{n} neu gerechnet", file=sys.stderr, flush=True)
|
||||
if len(cache) != vorher:
|
||||
_schreiben(cpfad, cache)
|
||||
|
||||
ergebnisse = rechne(entsch, bin_aufruf(kopie, opts, env), opts, cache, fortschritt=fortschritt)
|
||||
if len(cache) != vorher:
|
||||
_schreiben(cpfad, cache)
|
||||
haende = roentgen.haende_im_fenster(d["haende"], von, bis)
|
||||
by_id = {str(h.get("hand")): h for h in d["haende"] if h.get("hand")}
|
||||
daten = [datensatz(x, er, by_id) for x, er in zip(entsch, ergebnisse)]
|
||||
b = auswerten(daten, {"pid": lauf["pid"], "von": von, "bis": bis}, aus, len(haende))
|
||||
b["bin"] = {"quelle": quelle, "id": bin_id(quelle), "opts": opts}
|
||||
if fixtures:
|
||||
fo = os.path.join(ziel, "tests", "live_fixture")
|
||||
neu = fixture_vorschlaege(daten, fixture_haende(fo), schwelle)
|
||||
datei = os.path.join(fo, "vorschlag", f"audit-{von[:10]}.jsonl")
|
||||
if neu:
|
||||
os.makedirs(os.path.dirname(datei), exist_ok=True)
|
||||
with open(datei, "a", encoding="utf-8", newline="\n") as f:
|
||||
for z in neu:
|
||||
f.write(json.dumps(z, ensure_ascii=False) + "\n")
|
||||
b["fixture"] = {"neu": len(neu), "schwelle": schwelle, "datei": os.path.relpath(datei, ziel).replace("\\", "/")}
|
||||
_schreiben(os.path.join(ordner(ziel), f"lauf-{lauf['pid']}.json"), b)
|
||||
_schreiben(os.path.join(ordner(ziel), f"lauf-{lauf['pid']}.md"), markdown(b))
|
||||
return b
|
||||
|
||||
|
||||
def laufberichte(ziel):
|
||||
return [b for b in (_json_laden(p) for p in sorted(glob.glob(os.path.join(ordner(ziel), "lauf-*.json")))) if b.get("lauf")]
|
||||
|
||||
|
||||
def woche_schreiben(ziel, woche=None):
|
||||
berichte = laufberichte(ziel)
|
||||
if woche is None:
|
||||
zeiten = [b["lauf"]["von"] for b in berichte if b["lauf"].get("von")]
|
||||
if not zeiten:
|
||||
return {"fehler": "keine Laufberichte"}
|
||||
woche = iso_woche(max(zeiten))
|
||||
w = woche_summe(berichte, woche)
|
||||
_schreiben(os.path.join(ordner(ziel), f"woche-{woche}.json"), w)
|
||||
_schreiben(os.path.join(ordner(ziel), f"woche-{woche}.md"), markdown(w))
|
||||
return w
|
||||
|
||||
|
||||
def nach_lauf(wurzel, pid, ziel=None):
|
||||
"""Der Haken: ein Lauf, dann die Wochensumme. Fehler landen in archiv/audit/fehler.log."""
|
||||
ziel = ziel or wurzel
|
||||
try:
|
||||
b = lauf_bericht(wurzel, ziel, pid=pid, still=True)
|
||||
if "fehler" in b:
|
||||
raise RuntimeError(b["fehler"])
|
||||
woche_schreiben(ziel, iso_woche(b["lauf"]["von"]))
|
||||
return 0
|
||||
except Exception as e: # noqa: BLE001 - der Haken darf nie etwas anderes stören
|
||||
os.makedirs(ordner(ziel), exist_ok=True)
|
||||
with open(os.path.join(ordner(ziel), "fehler.log"), "a", encoding="utf-8") as f:
|
||||
f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} pid {pid}: {type(e).__name__}: {e}\n")
|
||||
return 1
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
a = argparse.ArgumentParser(description="Entscheidungs-Audit je Läuferlauf (D4)")
|
||||
a.add_argument("--wurzel", default=os.environ.get("AUDIT_WURZEL", BAUM), help="Baum mit Schatten-Log und archiv/lauf")
|
||||
a.add_argument("--ziel", default=None, help="Baum, in den Berichte und Fixture-Vorschläge geschrieben werden (Vorgabe: --wurzel)")
|
||||
a.add_argument("--pid")
|
||||
a.add_argument("--start", help="Ortszeit 'JJJJ-MM-TT HH:MM': der Lauf, der sie enthält")
|
||||
a.add_argument("--tag", help="JJJJ-MM-TT: jeder Lauf mit Entscheidungen an diesem Tag")
|
||||
a.add_argument("--woche", nargs="?", const="", help="nur die Wochensumme (JJJJ-Www, Vorgabe: jüngste)")
|
||||
a.add_argument("--nach-lauf", action="store_true", help="Haken-Modus: still, Fehler nach fehler.log")
|
||||
a.add_argument("--liste", action="store_true")
|
||||
a.add_argument("--bin")
|
||||
a.add_argument("--iters", type=int, default=OPTS_STANDARD["iters"])
|
||||
a.add_argument("--turn-iters", type=int, default=OPTS_STANDARD["turn_iters"])
|
||||
a.add_argument("--turn-combos", type=int, default=OPTS_STANDARD["turn_combos"])
|
||||
a.add_argument("--turn-cards", type=int, default=OPTS_STANDARD["turn_cards"])
|
||||
a.add_argument("--schwelle", type=float, default=SCHWELLE_FIXTURE_BB, help="Fixture-Vorschlag ab diesem Verlust (bb)")
|
||||
a.add_argument("--ohne-fixture", action="store_true")
|
||||
a.add_argument("--json", action="store_true")
|
||||
x = a.parse_args(argv)
|
||||
ziel = x.ziel or x.wurzel
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
if x.nach_lauf:
|
||||
return nach_lauf(x.wurzel, x.pid, ziel)
|
||||
if x.woche is not None:
|
||||
w = woche_schreiben(ziel, x.woche or None)
|
||||
print(json.dumps(w, ensure_ascii=False, indent=1) if x.json else (w.get("fehler") or markdown(w)))
|
||||
return 0
|
||||
d = roentgen.daten(x.wurzel)
|
||||
liste = roentgen.laeufe(d["schatten"])
|
||||
if x.liste:
|
||||
for r in liste:
|
||||
if r["entscheidungen"]:
|
||||
print(f"pid {r['pid']:>7} {r['von']} bis {r['bis']} {r['entscheidungen']} Anfragen")
|
||||
return 0
|
||||
opts = {"iters": x.iters, "turn_iters": x.turn_iters, "turn_combos": x.turn_combos, "turn_cards": x.turn_cards}
|
||||
pids = [x.pid] if x.pid else ([r["pid"] for r in liste if r["entscheidungen"] and r["von"].startswith(x.tag)]
|
||||
if x.tag else [None])
|
||||
letzte = None
|
||||
for pid in pids:
|
||||
print(f"Lauf {pid or '(letzter)'} ...", file=sys.stderr, flush=True)
|
||||
b = lauf_bericht(x.wurzel, ziel, pid=pid, start=x.start, opts=opts, d=d, fixtures=not x.ohne_fixture,
|
||||
schwelle=x.schwelle, binary=x.bin)
|
||||
if "fehler" in b:
|
||||
print(b["fehler"])
|
||||
return 1
|
||||
letzte = b
|
||||
if not x.tag:
|
||||
print(json.dumps(b, ensure_ascii=False, indent=1, default=str) if x.json else markdown(b))
|
||||
if letzte:
|
||||
w = woche_schreiben(ziel, iso_woche(letzte["lauf"]["von"]))
|
||||
if x.tag:
|
||||
print(json.dumps(w, ensure_ascii=False, indent=1, default=str) if x.json else markdown(w))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Entscheidungs-Audit (Plan D4) im Cockpit-Server (lesen/audit_lauf.py): eine Seite und JSON-Endpunkte.
|
||||
|
||||
/audit Seite: Lauf oder Woche wählen, Bericht (Summen, die 10 teuersten Spots)
|
||||
/api/audit?pid=.. {"status": "fertig"|"rechnet"|"fehler"|"fehlt", "bericht", "text", "stand"}
|
||||
ohne pid: der jüngste Laufbericht
|
||||
/api/audit?pid=..&neu=1 rechnet den Lauf (neu) im Hintergrund; der Cache macht es billig
|
||||
/api/audit/laeufe [{pid, von, bis, entscheidungen, bericht: bool}]
|
||||
/api/audit/woche?woche=JJJJ-Www Wochensumme (aus den Laufberichten; ohne woche: die jüngste)
|
||||
|
||||
Gelesen wird, was der Haken nach jedem Lauf schreibt (archiv/audit/lauf-<pid>.json). Ein Lauf ohne
|
||||
Bericht wird nur auf Anforderung (`neu=1`) gerechnet, in EINEM Hintergrundfaden (die Bin läuft in
|
||||
Priorität Idle), nie im Anfrage-Faden. Datenquelle: AUDIT_WURZEL, sonst dieser Baum.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
_w = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
_l = os.path.join(_w, "lesen")
|
||||
if _l not in sys.path:
|
||||
sys.path.append(_l)
|
||||
|
||||
_sperre = threading.Lock()
|
||||
_rechnet = {} # pid -> {"status", "fehler", "stand"}
|
||||
_faden = None
|
||||
|
||||
|
||||
def _wurzel():
|
||||
return os.environ.get("AUDIT_WURZEL") or _w
|
||||
|
||||
|
||||
def _bericht_laden(pid=None):
|
||||
import audit_lauf
|
||||
if pid is None:
|
||||
alle = audit_lauf.laufberichte(_wurzel())
|
||||
return max(alle, key=lambda b: b["lauf"].get("von") or "") if alle else None
|
||||
b = audit_lauf._json_laden(os.path.join(audit_lauf.ordner(_wurzel()), f"lauf-{pid}.json"))
|
||||
return b or None
|
||||
|
||||
|
||||
def _rechnen(pid):
|
||||
import audit_lauf
|
||||
try:
|
||||
b = audit_lauf.lauf_bericht(_wurzel(), pid=pid, still=True)
|
||||
if "fehler" in b:
|
||||
raise RuntimeError(b["fehler"])
|
||||
audit_lauf.woche_schreiben(_wurzel(), audit_lauf.iso_woche(b["lauf"]["von"]))
|
||||
with _sperre:
|
||||
_rechnet[str(pid)] = {"status": "fertig", "stand": time.time()}
|
||||
except Exception as e: # noqa: BLE001 - die Seite zeigt den Fehler, der Server bleibt stehen
|
||||
with _sperre:
|
||||
_rechnet[str(pid)] = {"status": "fehler", "fehler": f"{type(e).__name__}: {e}", "stand": time.time()}
|
||||
|
||||
|
||||
def anfordern(pid=None, neu=False):
|
||||
"""Stand für einen Lauf; `neu` stößt das Rechnen an (ein Faden für alles)."""
|
||||
global _faden
|
||||
import audit_lauf
|
||||
with _sperre:
|
||||
laeuft = _faden is not None and _faden.is_alive()
|
||||
st = dict(_rechnet.get(str(pid)) or {})
|
||||
if neu and pid and not laeuft:
|
||||
_rechnet[str(pid)] = {"status": "rechnet", "stand": time.time()}
|
||||
_faden = threading.Thread(target=_rechnen, args=(pid,), daemon=True, name="audit")
|
||||
_faden.start()
|
||||
st = dict(_rechnet[str(pid)])
|
||||
elif neu and laeuft and st.get("status") != "rechnet":
|
||||
st = {"status": "wartet", "text": "ein anderer Lauf wird gerade gerechnet ..."}
|
||||
b = _bericht_laden(pid)
|
||||
if st.get("status") in ("rechnet", "wartet", "fehler"):
|
||||
st.update({"bericht": b, "text": audit_lauf.markdown(b) if b else st.get("text", "rechnet ...")})
|
||||
return st
|
||||
if not b:
|
||||
return {"status": "fehlt", "text": "noch kein Bericht für diesen Lauf (neu rechnen stößt ihn an)", "bericht": None}
|
||||
return {"status": "fertig", "bericht": b, "text": audit_lauf.markdown(b), "stand": b.get("erstellt")}
|
||||
|
||||
|
||||
def laeufe():
|
||||
import audit_lauf
|
||||
import roentgen
|
||||
da = {str(b["lauf"].get("pid")) for b in audit_lauf.laufberichte(_wurzel())}
|
||||
liste = roentgen.laeufe(roentgen.daten(_wurzel())["schatten"])
|
||||
return [dict(r, bericht=str(r["pid"]) in da) for r in liste if r["entscheidungen"] > 0]
|
||||
|
||||
|
||||
def woche(w=None):
|
||||
import audit_lauf
|
||||
if w:
|
||||
b = audit_lauf._json_laden(os.path.join(audit_lauf.ordner(_wurzel()), f"woche-{w}.json"))
|
||||
else:
|
||||
alle = sorted(p for p in os.listdir(audit_lauf.ordner(_wurzel())) if p.startswith("woche-") and p.endswith(".json")) \
|
||||
if os.path.isdir(audit_lauf.ordner(_wurzel())) else []
|
||||
b = audit_lauf._json_laden(os.path.join(audit_lauf.ordner(_wurzel()), alle[-1])) if alle else {}
|
||||
if not b:
|
||||
return {"status": "fehlt", "text": "noch keine Wochensumme", "bericht": None}
|
||||
return {"status": "fertig", "bericht": b, "text": audit_lauf.markdown(b)}
|
||||
|
||||
|
||||
SEITE = """<!doctype html>
|
||||
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Entscheidungs-Audit</title>
|
||||
<style>
|
||||
:root{--bg:#fff;--fg:#1d1d1f;--mut:#6e6e73;--rand:#d2d2d7;--akzent:#0a62c9;--rot:#c9341f}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#1c1c1e;--fg:#f2f2f7;--mut:#98989d;--rand:#3a3a3c;--akzent:#64a8ff;--rot:#ff6b5a}}
|
||||
body{margin:0;padding:16px;background:var(--bg);color:var(--fg);font:14px/1.4 -apple-system,Segoe UI,sans-serif}
|
||||
h1{font-size:18px;margin:0 0 12px}h2{font-size:15px;margin:18px 0 6px}
|
||||
select,button{font:inherit;padding:4px 8px;background:var(--bg);color:var(--fg);border:1px solid var(--rand);border-radius:6px}
|
||||
#status{color:var(--mut);margin:8px 0}
|
||||
.kacheln{display:flex;flex-wrap:wrap;gap:8px;margin:8px 0}
|
||||
.k{border:1px solid var(--rand);border-radius:8px;padding:6px 10px;min-width:110px}
|
||||
.k b{display:block;font-size:18px;font-variant-numeric:tabular-nums}.k span{color:var(--mut);font-size:12px}
|
||||
.tab{overflow-x:auto}
|
||||
table{border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums}
|
||||
td,th{border-bottom:1px solid var(--rand);padding:3px 8px;text-align:left;vertical-align:top}
|
||||
td.z{text-align:right}.v{color:var(--rot);font-weight:600}
|
||||
pre{font:12px/1.45 ui-monospace,Consolas,monospace;overflow-x:auto;white-space:pre-wrap;border-top:1px solid var(--rand);padding-top:12px}
|
||||
</style></head><body>
|
||||
<h1>Entscheidungs-Audit (D4)</h1>
|
||||
<label>Bericht <select id="wahl"></select></label> <button id="neu">Lauf neu rechnen</button>
|
||||
<div id="status"></div>
|
||||
<div class="kacheln" id="kacheln"></div>
|
||||
<h2>Die 10 teuersten Entscheidungen</h2><div class="tab"><table id="top"></table></div>
|
||||
<h2>Je Street, Messlatte, Engine-Teil</h2><pre id="text">lädt ...</pre>
|
||||
<script>
|
||||
const $=id=>document.getElementById(id);let uhr=null;
|
||||
const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
async function liste(){
|
||||
const l=await (await fetch('/api/audit/laeufe')).json();
|
||||
$('wahl').innerHTML='<option value="woche">Woche (Summe)</option>'+l.slice().reverse().map(r=>
|
||||
`<option value="${r.pid}">pid ${r.pid} · ${r.von} – ${r.bis.slice(11)} · ${r.entscheidungen} Anfr.${r.bericht?'':' · ohne Bericht'}</option>`).join('');
|
||||
}
|
||||
function zeigen(r){
|
||||
const b=r.bericht;$('text').textContent=r.text||'';
|
||||
if(!b){$('kacheln').innerHTML='';$('top').innerHTML='';return;}
|
||||
const g=b.streets.GESAMT,h=b.haende||0;
|
||||
const k=[[g.verlust_bb.toFixed(1)+' bb','Verlust gesamt'],[h?(100*g.verlust_bb/h).toFixed(2):'-','bb/100 Hände'],
|
||||
[g.bewertet+' / '+g.n,'bewertet / Entscheidungen'],[h,'Hände']];
|
||||
for(const s of ['PREFLOP','FLOP','TURN','RIVER']){const x=b.streets[s];k.push([x.verlust_bb.toFixed(1)+' bb',s+' ('+x.bewertet+')']);}
|
||||
$('kacheln').innerHTML=k.map(([w,t])=>`<div class="k"><b>${esc(w)}</b><span>${esc(t)}</span></div>`).join('');
|
||||
$('top').innerHTML='<tr><th>#</th><th>Hand</th><th>Street</th><th>Karten / Brett</th><th>gespielt</th><th>besser</th><th>Verlust bb</th><th>Hand bb</th><th>Engine-Teil</th><th>Grund</th></tr>'+
|
||||
b.top.slice(0,10).map((t,i)=>`<tr><td class="z">${i+1}</td><td>${esc(t.hand)}<br><span style="color:var(--mut)">${esc(t.zeit)}</span></td><td>${esc(t.street)}</td>`+
|
||||
`<td>${esc(t.karten)} / ${esc(t.brett||'-')}</td><td>${esc(t.gespielt_als)}</td><td>${esc(t.beste)}</td><td class="z v">${t.verlust_bb.toFixed(2)}</td>`+
|
||||
`<td class="z">${t.ergebnis_bb==null?'-':t.ergebnis_bb.toFixed(1)}</td><td>${esc(t.wer_name||t.wer)}</td><td>${esc((t.grund||'').slice(0,90))}</td></tr>`).join('');
|
||||
}
|
||||
async function holen(neu){
|
||||
clearTimeout(uhr);const w=$('wahl').value;
|
||||
try{
|
||||
const url=w==='woche'?'/api/audit/woche':'/api/audit?pid='+encodeURIComponent(w)+(neu?'&neu=1':'');
|
||||
const r=await (await fetch(url)).json();zeigen(r);
|
||||
$('status').textContent=r.status==='fertig'?'fertig'+(r.stand?' ('+r.stand+')':''):r.status==='fehler'?'Fehler: '+r.fehler:
|
||||
r.status==='rechnet'?'wird gerechnet (Bin, Priorität Idle) ...':r.text||r.status;
|
||||
if(r.status==='rechnet'||r.status==='wartet') uhr=setTimeout(()=>holen(false),4000);
|
||||
}catch(e){$('status').textContent='Server nicht erreichbar';uhr=setTimeout(()=>holen(false),5000);}
|
||||
}
|
||||
$('wahl').onchange=()=>holen(false);$('neu').onclick=()=>holen(true);
|
||||
liste().then(()=>holen(false));
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
def _js(x):
|
||||
return 200, json.dumps(x, ensure_ascii=False, default=str).encode("utf-8"), "application/json; charset=utf-8"
|
||||
|
||||
|
||||
def antwort(pfad, query=""):
|
||||
"""(code, daten, art) für unsere Pfade, sonst None."""
|
||||
q = parse_qs(query or "")
|
||||
if pfad == "/audit":
|
||||
return 200, SEITE.encode("utf-8"), "text/html; charset=utf-8"
|
||||
if pfad == "/api/audit/laeufe":
|
||||
return _js(laeufe())
|
||||
if pfad == "/api/audit/woche":
|
||||
return _js(woche((q.get("woche") or [None])[0]))
|
||||
if pfad == "/api/audit":
|
||||
pid = (q.get("pid") or [None])[0]
|
||||
neu = (q.get("neu") or ["0"])[0] == "1"
|
||||
return _js(anfordern(pid, neu))
|
||||
return None
|
||||
@@ -6,6 +6,7 @@
|
||||
/foto/<name>.png Fotos aus sicht/scratch/
|
||||
/sendung/<name>.html, /api/sendung die Seiten der Sendung fuer OBS (sicht/sendung_seiten.py)
|
||||
/roentgen, /api/roentgen Engine-Roentgen je Lauf (sicht/roentgen_seite.py, lesen/roentgen.py)
|
||||
/audit, /api/audit Entscheidungs-Audit D4 je Lauf und Woche (sicht/audit_seite.py, lesen/audit_lauf.py)
|
||||
|
||||
Leitsatz: das Cockpit liest nur. Ein Hintergrundfaden ruft alle ~0.5 s quellen.lesen() und
|
||||
ansicht.bauen() auf; wirft eines davon (oder fehlt das Modul), geht die leere Ansicht raus. Der
|
||||
@@ -24,6 +25,7 @@ HIER = os.path.dirname(os.path.abspath(__file__))
|
||||
if HIER not in sys.path:
|
||||
sys.path.insert(0, HIER)
|
||||
import roentgen_seite
|
||||
import audit_seite
|
||||
import sendung_seiten
|
||||
import steuern
|
||||
import ws
|
||||
@@ -239,6 +241,10 @@ def _handler(cockpit):
|
||||
seite = roentgen_seite.antwort(pfad, urlparse(self.path).query)
|
||||
if seite:
|
||||
return self._senden(*seite)
|
||||
if pfad == "/audit" or pfad.startswith("/api/audit"):
|
||||
seite = audit_seite.antwort(pfad, urlparse(self.path).query)
|
||||
if seite:
|
||||
return self._senden(*seite)
|
||||
with cockpit.sperre:
|
||||
teile = dict(cockpit.teile)
|
||||
seite = sendung_seiten.antwort(pfad, teile) # die Seiten der Sendung fuer OBS
|
||||
|
||||
+18
-6
@@ -8,11 +8,14 @@
|
||||
//! Output line (one per input line, same order):
|
||||
//! `{"id", "status": "ok"|"skip", "reason"?, "source": "blueprint"|"modell", "first", "class",
|
||||
//! "classes", "taken", "size_gap", "acts": [{"act", "to"?, "p", "ev"}], "ev_best", "ev_mix", "ev_taken",
|
||||
//! "loss", "loss_bb", "off_line", "hero_in_range", "exploitability", "bb"}`. EVs and loss are chips of the spot (river
|
||||
//! on, solver scale); `loss_bb` is `loss / bigBlind`.
|
||||
//! "loss", "loss_bb", "off_line", "hero_in_range", "exploitability", "bb", "method", "note"}`. EVs and
|
||||
//! loss are chips of the spot (from the start of the street, solver scale); `loss_bb` is `loss / bigBlind`.
|
||||
//! `method`: `river_game`, `turn_river_game`, `jam_preis`, `push_fold`, `allin_equity` (see
|
||||
//! `engine::audit`, `engine::audit_turn`, `engine::audit_allin`).
|
||||
//!
|
||||
//! Use: `audit [--iters N] [in.jsonl] > out.jsonl` (stdin without a file). Single thread. Ranges come
|
||||
//! from the blueprint when `$GRUNDSTRATEGIE` is set and the spot is scenario S1, else the range model.
|
||||
//! Use: `audit [--iters N] [--turn-iters N] [--turn-combos N] [--turn-cards N] [in.jsonl] > out.jsonl`
|
||||
//! (stdin without a file). Single thread. Ranges come from the blueprint when `$GRUNDSTRATEGIE` is set
|
||||
//! and the spot is scenario S1, else the range model.
|
||||
//! Run at priority Idle (CLAUDE.md "Messlaeufe").
|
||||
|
||||
use rechner::cfr::river_game::Act;
|
||||
@@ -115,23 +118,32 @@ fn one(line: &str, opts: Opts) -> Value {
|
||||
("hero_in_range".to_string(), Value::Bool(a.hero_in_range)),
|
||||
("exploitability".to_string(), num(a.exploitability)),
|
||||
("bb".to_string(), num(bb)),
|
||||
("method".to_string(), Value::String(a.method.to_string())),
|
||||
("note".to_string(), Value::String(a.note.clone())),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
set_hook(Box::new(|_| {}));
|
||||
let mut iters = Opts::default().iters;
|
||||
let mut opts = Opts::default();
|
||||
let mut iters = opts.iters;
|
||||
let mut file: Option<String> = None;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
if a == "--iters" {
|
||||
iters = args.next().and_then(|s| s.parse().ok()).unwrap_or(iters);
|
||||
} else if a == "--turn-iters" {
|
||||
opts.turn_iters = args.next().and_then(|s| s.parse().ok()).unwrap_or(opts.turn_iters);
|
||||
} else if a == "--turn-combos" {
|
||||
opts.turn_combos = args.next().and_then(|s| s.parse().ok()).unwrap_or(opts.turn_combos);
|
||||
} else if a == "--turn-cards" {
|
||||
opts.turn_cards = args.next().and_then(|s| s.parse().ok()).unwrap_or(opts.turn_cards);
|
||||
} else {
|
||||
file = Some(a);
|
||||
}
|
||||
}
|
||||
let opts = Opts { iters };
|
||||
opts.iters = iters;
|
||||
let reader: Box<dyn BufRead> = match &file {
|
||||
Some(p) => Box::new(io::BufReader::new(std::fs::File::open(p).expect("open input"))),
|
||||
None => Box::new(io::BufReader::new(io::stdin())),
|
||||
|
||||
@@ -654,6 +654,64 @@ impl TrSolver {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hero (player 0) combo `hand` at hero's turn decision `node`: the value of every child of the
|
||||
/// node against `strategy` (hero plays `strategy` afterwards too), with the villain's range
|
||||
/// conditioned on the turn line from the root (its own probabilities along the way). Chips per
|
||||
/// deal, payoff scale of the game (from the start of the turn): only differences between children
|
||||
/// mean anything. The flag says the conditioned villain range was empty (the line is off the
|
||||
/// equilibrium) and the unconditioned range was used. `None`: `node` is not a hero turn decision
|
||||
/// reached from the root on the turn, or no villain combo is left against `hand`.
|
||||
pub fn hand_action_values(&self, strategy: &TrStrategy, node: usize, hand: usize) -> Option<(Vec<f64>, bool)> {
|
||||
if hand >= self.n[0] {
|
||||
return None;
|
||||
}
|
||||
let kids = match &self.game.nodes[node] {
|
||||
TNode::Dec { player: 0, street: 0, kids } => kids.clone(),
|
||||
_ => return None,
|
||||
};
|
||||
let mut path = Vec::new();
|
||||
if !self.turn_path(self.game.root, node, &mut path) {
|
||||
return None;
|
||||
}
|
||||
let mut opp = self.weights[1].clone();
|
||||
for &(at, k) in &path {
|
||||
if let TNode::Dec { player: 1, .. } = self.game.nodes[at] {
|
||||
for (j, w) in opp.iter_mut().enumerate() {
|
||||
*w *= strategy.row(at, 0, j)[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut off_line = false;
|
||||
if self.disjoint(0, &opp)[hand] < 1e-12 {
|
||||
off_line = true;
|
||||
opp = self.weights[1].clone();
|
||||
}
|
||||
let mass = self.disjoint(0, &opp)[hand];
|
||||
if mass <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let own = vec![1.0; self.n[0]];
|
||||
let values = kids.iter().map(|&kid| self.follow(strategy, kid, 0, &opp, NO_CARD, &own)[hand] / mass).collect();
|
||||
Some((values, off_line))
|
||||
}
|
||||
|
||||
/// The `(node, child)` steps from `node` to `target` through turn decisions only.
|
||||
fn turn_path(&self, node: usize, target: usize, out: &mut Vec<(usize, usize)>) -> bool {
|
||||
if node == target {
|
||||
return true;
|
||||
}
|
||||
if let TNode::Dec { street: 0, kids, .. } = &self.game.nodes[node] {
|
||||
for (k, &kid) in kids.iter().enumerate() {
|
||||
out.push((node, k));
|
||||
if self.turn_path(kid, target, out) {
|
||||
return true;
|
||||
}
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The river card with this bit (index into the enumerated cards), if enumerated.
|
||||
pub fn card_index(&self, bit: u64) -> Option<usize> {
|
||||
self.rc.iter().position(|c| c.bit == bit)
|
||||
|
||||
+38
-18
@@ -24,9 +24,13 @@
|
||||
//! is blueprint scenario S1) where available, else the engine's own range model for both players
|
||||
//! (`RangeSource::Model`), exactly as `river_subgame::river_game_decision` builds them.
|
||||
//!
|
||||
//! # Turn hook
|
||||
//! # Other streets
|
||||
//!
|
||||
//! `audit_turn` is the place for the turn+river solver (built elsewhere). It currently skips.
|
||||
//! - **Turn** (`engine::audit_turn`): the turn+river game over real combos (`cfr::turn_river_game`,
|
||||
//! the E3 solver), same definitions, chips from the start of the turn.
|
||||
//! - **Preflop and flop** (`engine::audit_allin`): only where a price decides alone - facing an all-in
|
||||
//! (equity against the jammer's range against the price), and a first-in push/fold at short stacks
|
||||
//! (the Nash push/fold game the frozen charts come from). Everything else is skipped with a reason.
|
||||
|
||||
use crate::card::Card;
|
||||
use crate::cfr::river_game::{build, Act, Bets};
|
||||
@@ -72,8 +76,10 @@ impl RangeSource {
|
||||
/// Why a decision cannot be audited.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Skip {
|
||||
/// Turn (hook for the turn+river solver) or earlier streets.
|
||||
/// A street without a yardstick here.
|
||||
Street(Street),
|
||||
/// Preflop / flop spot that no price alone decides (no all-in, no short-stack push/fold).
|
||||
NotCovered(&'static str),
|
||||
Multiway,
|
||||
NoRange(&'static str),
|
||||
/// The taken action does not fit the node (e.g. a fold with nothing to call).
|
||||
@@ -86,6 +92,7 @@ impl Skip {
|
||||
pub fn text(&self) -> String {
|
||||
match self {
|
||||
Skip::Street(s) => format!("street {s:?} not audited"),
|
||||
Skip::NotCovered(w) => format!("not covered: {w}"),
|
||||
Skip::Multiway => "multiway".to_string(),
|
||||
Skip::NoRange(w) => format!("no range: {w}"),
|
||||
Skip::Illegal(w) => format!("illegal: {w}"),
|
||||
@@ -128,38 +135,52 @@ pub struct Audit {
|
||||
pub hero_in_range: bool,
|
||||
/// Exploitability of the solved game at the end of the run (payoff units), a convergence check.
|
||||
pub exploitability: f64,
|
||||
/// Which yardstick priced the decision: `river_game`, `turn_river_game`, `jam_preis`,
|
||||
/// `allin_equity`, `push_fold`.
|
||||
pub method: &'static str,
|
||||
/// What the yardstick assumed, in a few words (reference range, depth, equity vs price).
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
/// Options for one audit run.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Opts {
|
||||
/// CFR+ iterations of the river game.
|
||||
pub iters: u32,
|
||||
/// CFR+ iterations of the turn+river game.
|
||||
pub turn_iters: u32,
|
||||
/// Most combos per player in the turn+river game.
|
||||
pub turn_combos: usize,
|
||||
/// River cards enumerated in the turn+river game (of 44-46).
|
||||
pub turn_cards: usize,
|
||||
}
|
||||
|
||||
impl Default for Opts {
|
||||
fn default() -> Opts {
|
||||
Opts { iters: 10_000 }
|
||||
Opts { iters: 10_000, turn_iters: 200, turn_combos: 200, turn_cards: 10 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Audit one decision. River: the full river game. Turn: hook (`audit_turn`).
|
||||
/// Audit one decision. River: the full river game. Turn: the turn+river game. Preflop and flop:
|
||||
/// all-in prices and short-stack push/fold (`audit_allin`).
|
||||
pub fn audit(spot: &Spot, taken: Taken, opts: Opts) -> Result<Audit, Skip> {
|
||||
match spot.street {
|
||||
Street::River => audit_river(spot, taken, opts),
|
||||
Street::Turn => audit_turn(spot, taken, opts),
|
||||
s => Err(Skip::Street(s)),
|
||||
Street::Preflop => crate::engine::audit_allin::audit_preflop(spot, taken),
|
||||
Street::Flop => crate::engine::audit_allin::audit_flop(spot, taken),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook for the turn+river solver. Not built here: a turn decision is skipped for now.
|
||||
pub fn audit_turn(_spot: &Spot, _taken: Taken, _opts: Opts) -> Result<Audit, Skip> {
|
||||
Err(Skip::Street(Street::Turn))
|
||||
/// The turn: `engine::audit_turn` (turn+river game over real combos).
|
||||
pub fn audit_turn(spot: &Spot, taken: Taken, opts: Opts) -> Result<Audit, Skip> {
|
||||
crate::engine::audit_turn::audit_turn(spot, taken, opts)
|
||||
}
|
||||
|
||||
type Weighted = Vec<(Vec<Card>, f64)>;
|
||||
pub(crate) type Weighted = Vec<(Vec<Card>, f64)>;
|
||||
|
||||
/// The two weighted range lists of the spot and where they came from.
|
||||
fn ranges(spot: &Spot, villain: &Villain) -> Option<(Weighted, Weighted, RangeSource)> {
|
||||
pub(crate) fn ranges(spot: &Spot, villain: &Villain) -> Option<(Weighted, Weighted, RangeSource)> {
|
||||
if crate::blueprint::ranges::grundstrategie().is_some() {
|
||||
if let Some((h, v)) = crate::blueprint::ranges::gewichtete_listen(spot) {
|
||||
return Some((h, v, RangeSource::Blueprint));
|
||||
@@ -325,11 +346,13 @@ pub fn audit_game(n: usize, chance: Vec<f64>, bets: &Bets, line: &[Act], taken:
|
||||
off_line,
|
||||
hero_in_range: true,
|
||||
exploitability: solved.final_exploitability,
|
||||
method: "river_game",
|
||||
note: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The `(node, child)` steps from `node` down to `target`.
|
||||
fn path_to(tree: &Tree, node: usize, target: usize, out: &mut Vec<(usize, usize)>) -> bool {
|
||||
pub(crate) fn path_to(tree: &Tree, node: usize, target: usize, out: &mut Vec<(usize, usize)>) -> bool {
|
||||
if node == target {
|
||||
return true;
|
||||
}
|
||||
@@ -347,7 +370,7 @@ fn path_to(tree: &Tree, node: usize, target: usize, out: &mut Vec<(usize, usize)
|
||||
|
||||
/// Unnormalised value for hero (class `b`) of the subtree at `node`, summed over the villain's class
|
||||
/// weights `w`: hero plays `sigma` for class `b`, the villain's weights shrink by its probabilities.
|
||||
fn value(tree: &Tree, sigma: &Strategy, node: usize, w: &[f64], b: usize) -> f64 {
|
||||
pub(crate) fn value(tree: &Tree, sigma: &Strategy, node: usize, w: &[f64], b: usize) -> f64 {
|
||||
let n = tree.classes;
|
||||
match &tree.nodes[node] {
|
||||
Node::Terminal(p) => w
|
||||
@@ -487,7 +510,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_set_facing_a_pot_bet_loses_by_folding_not_by_calling() {
|
||||
let spot = river_spot("Ah Kd 7c 2s 9h", "Ac Ad", 20.0, 10.0);
|
||||
let opts = Opts { iters: 6_000 };
|
||||
let opts = Opts { iters: 6_000, ..Opts::default() };
|
||||
let call = audit(&spot, Taken::Call, opts).expect("auditable");
|
||||
let fold = audit(&spot, Taken::Fold, opts).expect("auditable");
|
||||
assert_eq!(call.source, RangeSource::Model);
|
||||
@@ -496,13 +519,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_and_multiway_are_skipped_not_guessed() {
|
||||
fn multiway_and_illegal_are_skipped_not_guessed() {
|
||||
let mut spot = river_spot("Ah Kd 7c 2s 9h", "Ac Ad", 20.0, 10.0);
|
||||
spot.villains.push(Villain { seat: 3, stack: 100.0, folded: false, profile: None });
|
||||
assert_eq!(audit(&spot, Taken::Call, Opts::default()), Err(Skip::Multiway));
|
||||
let mut turn = river_spot("Ah Kd 7c 2s", "Ac Ad", 20.0, 10.0);
|
||||
turn.street = Street::Turn;
|
||||
assert_eq!(audit(&turn, Taken::Call, Opts::default()), Err(Skip::Street(Street::Turn)));
|
||||
let illegal = river_spot("Ah Kd 7c 2s 9h", "Ac Ad", 20.0, 0.0);
|
||||
assert!(matches!(audit(&illegal, Taken::Fold, Opts::default()), Err(Skip::Illegal(_))));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
//! Decision audit (plan D4) on preflop and flop: only where a price decides alone.
|
||||
//!
|
||||
//! There is no preflop or flop solver over real lines yet (plan E). What can be priced honestly:
|
||||
//!
|
||||
//! - **Preflop, facing an all-in** (open-jam, or a jam over hero's raise, heads-up with the jammer):
|
||||
//! `EV(call) = equity x final pot - call`, `EV(fold) = 0`. The equity is against the jammer seat's
|
||||
//! Nash PUSH range at the jam depth, clamped to the deepest frozen table (25 bb), exact per class
|
||||
//! with card removal (`preflop::open_jam`): the widest range a jam of that size can rationally hold.
|
||||
//! A raise against an all-in is priced as the call. Method `jam_preis`.
|
||||
//! - **Preflop, first in at a short stack** (no raise and no limp before hero, effective stack within
|
||||
//! the push/fold charts, at most 25 bb): push or fold in the Nash push/fold game the frozen charts
|
||||
//! are solved from (`cfr::push_fold_game`, solved here), EV of both against the solved callers.
|
||||
//! A first-in raise of at least half the stack counts as the push; a smaller open or a limp is not
|
||||
//! a push/fold decision and is skipped. Method `push_fold`.
|
||||
//! - **Flop, facing an all-in** heads-up (the villain has nothing behind, or the call puts hero all-in):
|
||||
//! `EV(call) = equity x final pot - call` with the equity exactly enumerated over all turn and river
|
||||
//! cards against the villain's range (blueprint where it knows the spot, else the range model; the
|
||||
//! same lists as the river audit). Method `allin_equity`.
|
||||
//!
|
||||
//! Everything else on these streets is skipped (`Skip::NotCovered`) and counted by the report.
|
||||
//! EVs are chips of the spot; only differences between actions mean anything.
|
||||
|
||||
use crate::card::Card;
|
||||
use crate::cfr::chart_deck::ChartDeck;
|
||||
use crate::cfr::environment::Environment;
|
||||
use crate::cfr::hand_class::class_of;
|
||||
use crate::cfr::push_fold_game::push_fold_tree;
|
||||
use crate::cfr::river_game::Act;
|
||||
use crate::cfr::solve::solve;
|
||||
use crate::cfr::tree::Node;
|
||||
use crate::engine::audit::{ranges, value, ActEv, Audit, RangeSource, Skip, Taken};
|
||||
use crate::game::{SeenAction, Spot, Street};
|
||||
use crate::hand::fast7;
|
||||
use crate::preflop::first_raiser::{preflop_callers, raise_count};
|
||||
use crate::preflop::generated_lookup::{has_charts, push_depth_range, seat_of};
|
||||
use crate::preflop::open_jam::{depth_bb, equity_vs, jam_range, open_jam, price, OpenJam};
|
||||
use crate::preflop::seat_position::seat_position;
|
||||
use crate::rng::Rng;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// A stack at or below this is gone.
|
||||
const EMPTY: f64 = 1e-9;
|
||||
/// CFR iterations of the push/fold game (169 classes, a handful of nodes: milliseconds).
|
||||
const PUSH_FOLD_ITERS: u32 = 4_000;
|
||||
|
||||
fn environment(deck: ChartDeck) -> &'static Environment {
|
||||
static FULL: OnceLock<Environment> = OnceLock::new();
|
||||
static SHORT: OnceLock<Environment> = OnceLock::new();
|
||||
match deck {
|
||||
ChartDeck::Full => FULL.get_or_init(|| Environment::frozen_for(ChartDeck::Full)),
|
||||
ChartDeck::Short => SHORT.get_or_init(|| Environment::frozen_for(ChartDeck::Short)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Chips `seat` has in on `street` (its largest street total in the history).
|
||||
fn put_in(spot: &Spot, seat: u8, street: Street) -> f64 {
|
||||
spot.history
|
||||
.iter()
|
||||
.filter(|r| r.street == street && r.seat == seat)
|
||||
.filter_map(|r| r.amount)
|
||||
.filter(|a| a.is_finite() && *a > 0.0)
|
||||
.fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// A two-action audit (fold / continue) from the two EVs.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn two_way(fold_ev: f64, go: Act, go_ev: f64, taken_go: bool, source: RangeSource, method: &'static str, note: String, first: usize) -> Audit {
|
||||
let best_go = go_ev >= fold_ev;
|
||||
let acts = vec![
|
||||
ActEv { act: Act::Fold, prob: if best_go { 0.0 } else { 1.0 }, ev: fold_ev },
|
||||
ActEv { act: go, prob: if best_go { 1.0 } else { 0.0 }, ev: go_ev },
|
||||
];
|
||||
let taken = usize::from(taken_go);
|
||||
let ev_best = fold_ev.max(go_ev);
|
||||
let ev_taken = acts[taken].ev;
|
||||
Audit {
|
||||
source,
|
||||
class: 0,
|
||||
classes: 0,
|
||||
nodes: 0,
|
||||
first,
|
||||
acts,
|
||||
taken,
|
||||
size_gap: 0.0,
|
||||
ev_best,
|
||||
ev_mix: ev_best,
|
||||
ev_taken,
|
||||
loss: (ev_best - ev_taken).max(0.0),
|
||||
off_line: false,
|
||||
hero_in_range: true,
|
||||
exploitability: 0.0,
|
||||
method,
|
||||
note,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hero continues against an all-in (call, or a raise priced as the call), or folds.
|
||||
fn continues(taken: Taken, to_call: f64) -> Result<bool, Skip> {
|
||||
match taken {
|
||||
Taken::Fold => Ok(false),
|
||||
Taken::Call | Taken::Aggress(_) => Ok(true),
|
||||
Taken::Check if to_call > 0.0 => Err(Skip::Illegal("check facing a bet")),
|
||||
Taken::Check => Err(Skip::Illegal("check facing an all-in")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last preflop raise or jam and its seat, when it left the raiser with nothing behind (or
|
||||
/// committed: the raise is at least the stack kept).
|
||||
fn facing_jam(spot: &Spot) -> Option<OpenJam> {
|
||||
if let Some(j) = open_jam(spot) {
|
||||
return preflop_callers(spot).is_empty().then_some(j);
|
||||
}
|
||||
let r = spot
|
||||
.history
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|r| r.street == Street::Preflop && matches!(r.action, SeenAction::Raise | SeenAction::AllIn))?;
|
||||
if r.seat == spot.hero_seat || spot.live_villains().count() != 1 {
|
||||
return None;
|
||||
}
|
||||
let to = r.amount.filter(|a| a.is_finite() && *a > spot.big_blind)?;
|
||||
let v = spot.villains.iter().find(|v| v.seat == r.seat)?;
|
||||
let all_in = r.action == SeenAction::AllIn || v.stack <= EMPTY;
|
||||
if !(all_in || to >= v.stack) || v.folded {
|
||||
return None;
|
||||
}
|
||||
Some(OpenJam { seat: r.seat, raised_to: to, total: to + if all_in { 0.0 } else { v.stack } })
|
||||
}
|
||||
|
||||
/// Audit a preflop decision: facing an all-in, or a first-in push/fold at a short stack.
|
||||
pub fn audit_preflop(spot: &Spot, taken: Taken) -> Result<Audit, Skip> {
|
||||
if spot.street != Street::Preflop {
|
||||
return Err(Skip::Street(spot.street));
|
||||
}
|
||||
if !has_charts(spot.variant) || spot.hero_cards.len() != 2 {
|
||||
return Err(Skip::NotCovered("preflop: no charts for this variant"));
|
||||
}
|
||||
if spot.to_call > 0.0 {
|
||||
if let Some(jam) = facing_jam(spot) {
|
||||
return price_jam(spot, taken, &jam);
|
||||
}
|
||||
}
|
||||
if raise_count(spot) == 0 && preflop_callers(spot).is_empty() {
|
||||
return push_or_fold(spot, taken);
|
||||
}
|
||||
Err(Skip::NotCovered("preflop: no all-in and no short-stack push/fold"))
|
||||
}
|
||||
|
||||
fn price_jam(spot: &Spot, taken: Taken, jam: &OpenJam) -> Result<Audit, Skip> {
|
||||
let go = continues(taken, spot.to_call)?;
|
||||
let depth = depth_bb(spot, jam);
|
||||
let (membership, width) = jam_range(spot, jam, depth).ok_or(Skip::NoRange("jammer seat has no push chart"))?;
|
||||
let equity = equity_vs(spot, &membership).ok_or(Skip::NoRange("hero class"))?;
|
||||
let (call, pot) = price(spot, jam);
|
||||
if !(call > 0.0 && pot > 0.0) {
|
||||
return Err(Skip::NotCovered("preflop: nothing to call"));
|
||||
}
|
||||
let table = depth.min(push_depth_range().1);
|
||||
let behind = spot.live_villains().count() > 1;
|
||||
let note = format!(
|
||||
"equity {equity:.3} vs Nash push {} {table:.0}bb (top {:.0}%), price {:.3}{}",
|
||||
seat_position(spot, jam.seat).label(),
|
||||
100.0 * width,
|
||||
call / pot,
|
||||
if behind { "; players behind not modelled" } else { "" }
|
||||
);
|
||||
Ok(two_way(0.0, Act::Call, equity * pot - call, go, RangeSource::Model, "jam_preis", note, 1))
|
||||
}
|
||||
|
||||
fn push_or_fold(spot: &Spot, taken: Taken) -> Result<Audit, Skip> {
|
||||
let seat = seat_of(seat_position(spot, spot.hero_seat)).ok_or(Skip::NotCovered("preflop: big blind is never first in"))?;
|
||||
let hero_total = put_in(spot, spot.hero_seat, Street::Preflop) + spot.hero_stack.max(0.0);
|
||||
let deepest = spot
|
||||
.live_villains()
|
||||
.map(|v| v.stack.max(0.0) + put_in(spot, v.seat, Street::Preflop))
|
||||
.fold(0.0, f64::max);
|
||||
let depth = hero_total.min(deepest) / spot.big_blind;
|
||||
let (lo, hi) = push_depth_range();
|
||||
if !(depth.is_finite() && depth <= hi) {
|
||||
return Err(Skip::NotCovered("preflop: stack deeper than the push/fold charts"));
|
||||
}
|
||||
let push = match taken {
|
||||
Taken::Fold => false,
|
||||
Taken::Aggress(to) if to >= 0.5 * hero_total => true,
|
||||
Taken::Check => return Err(Skip::Illegal("check first in")),
|
||||
_ => return Err(Skip::NotCovered("preflop: short-stack open that is no jam")),
|
||||
};
|
||||
let deck = ChartDeck::of(spot.variant).ok_or(Skip::NotCovered("preflop: no charts for this variant"))?;
|
||||
let env = environment(deck);
|
||||
let class = class_of(spot.hero_cards[0], spot.hero_cards[1]).ok_or(Skip::NoRange("hero class"))?;
|
||||
let tree = push_fold_tree(env, seat, depth.max(lo).max(1.5)).map_err(|_| Skip::NoRange("push/fold tree"))?;
|
||||
let solved = solve(&tree, PUSH_FOLD_ITERS, Rng::seeded(spot.seed));
|
||||
let n = tree.classes;
|
||||
let w: Vec<f64> = (0..n).map(|j| tree.chance[class * n + j]).collect();
|
||||
let mass: f64 = w.iter().sum();
|
||||
if mass <= 0.0 {
|
||||
return Err(Skip::NoRange("hero class has no deals"));
|
||||
}
|
||||
let kids = match &tree.nodes[tree.root] {
|
||||
Node::Decision { children, .. } if children.len() == 2 => children.clone(),
|
||||
_ => return Err(Skip::LineLeftTree),
|
||||
};
|
||||
let bb = spot.big_blind;
|
||||
let fold_ev = value(&tree, &solved.strategy, kids[0], &w, class) / mass * bb;
|
||||
let push_ev = value(&tree, &solved.strategy, kids[1], &w, class) / mass * bb;
|
||||
let note = format!("Nash push/fold {} {depth:.1}bb (6-max model)", seat.label());
|
||||
let mut a = two_way(fold_ev, Act::Raise(hero_total), push_ev, push, RangeSource::Model, "push_fold", note, 0);
|
||||
a.exploitability = solved.final_exploitability * bb;
|
||||
a.class = class;
|
||||
a.classes = n;
|
||||
a.nodes = tree.nodes.len();
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// Hero's equity against a weighted list on `board`, every remaining card enumerated, card removal exact.
|
||||
pub fn equity_vs_list(hero: &[Card], board: &[Card], list: &[(Vec<Card>, f64)]) -> Option<f64> {
|
||||
let h = fast7::mask(hero);
|
||||
let b = fast7::mask(board);
|
||||
if hero.len() != 2 || h & b != 0 || board.len() > 5 || board.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let missing = 5 - board.len();
|
||||
let deck: Vec<u64> = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|c| c & (h | b) == 0).collect();
|
||||
let mut runs: Vec<u64> = Vec::new();
|
||||
match missing {
|
||||
0 => runs.push(0),
|
||||
1 => runs.extend(deck.iter().copied()),
|
||||
_ => {
|
||||
for i in 0..deck.len() {
|
||||
for j in i + 1..deck.len() {
|
||||
runs.push(deck[i] | deck[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mut won, mut total) = (0.0f64, 0.0f64);
|
||||
for (c, w) in list {
|
||||
if c.len() != 2 || !(*w > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let v = fast7::mask(c);
|
||||
if v & (h | b) != 0 || v.count_ones() != 2 {
|
||||
continue;
|
||||
}
|
||||
for r in &runs {
|
||||
if r & v != 0 {
|
||||
continue;
|
||||
}
|
||||
let (sh, sv) = (fast7::score(h | b | r), fast7::score(v | b | r));
|
||||
won += w * if sh > sv { 1.0 } else if sh == sv { 0.5 } else { 0.0 };
|
||||
total += w;
|
||||
}
|
||||
}
|
||||
(total > 0.0).then(|| won / total)
|
||||
}
|
||||
|
||||
/// Audit a flop decision: only heads-up facing an all-in.
|
||||
pub fn audit_flop(spot: &Spot, taken: Taken) -> Result<Audit, Skip> {
|
||||
if spot.street != Street::Flop {
|
||||
return Err(Skip::Street(spot.street));
|
||||
}
|
||||
if spot.live_villains().count() != 1 {
|
||||
return Err(Skip::Multiway);
|
||||
}
|
||||
let villain = spot.live_villains().next().ok_or(Skip::Multiway)?;
|
||||
if !(spot.to_call > 0.0 && (villain.stack <= EMPTY || spot.to_call >= spot.hero_stack - EMPTY)) {
|
||||
return Err(Skip::NotCovered("flop without all-in: no flop solver yet (plan E)"));
|
||||
}
|
||||
let go = continues(taken, spot.to_call)?;
|
||||
let gated = crate::engine::read_gate::gate_reads(spot);
|
||||
let (_, list, source) = ranges(&gated, villain).ok_or(Skip::NoRange("range lists"))?;
|
||||
let equity = equity_vs_list(&spot.hero_cards, &spot.board, &list).ok_or(Skip::NoRange("equity"))?;
|
||||
let call = spot.to_call.min(spot.hero_stack);
|
||||
let refund = (spot.to_call - spot.hero_stack).max(0.0);
|
||||
let pot = spot.pot - refund + call;
|
||||
let note = format!("equity {equity:.3} vs {} villain range ({} combos), price {:.3}", source.name(), list.len(), call / pot);
|
||||
Ok(two_way(0.0, Act::Call, equity * pot - call, go, source, "allin_equity", note, 1))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::game::{ActionKind, ActionRecord, Villain};
|
||||
use crate::variant::Variant;
|
||||
|
||||
fn rec(street: Street, seat: u8, action: SeenAction, amount: Option<f64>) -> ActionRecord {
|
||||
ActionRecord { street, seat, action, amount }
|
||||
}
|
||||
|
||||
/// Six-max, hero `hero` in seat 3 (UTG side), seat 1 open-jams `jam`, everybody else folded.
|
||||
fn facing_open_jam(hero: &str, jam: f64, stack: f64) -> Spot {
|
||||
Spot {
|
||||
variant: Variant::Nlhe,
|
||||
big_blind: 1.0,
|
||||
seats: 6,
|
||||
hero_seat: 2,
|
||||
button_seat: Some(6),
|
||||
hero_cards: Card::parse_list(hero).unwrap(),
|
||||
board: Vec::new(),
|
||||
street: Street::Preflop,
|
||||
pot: jam + 1.5,
|
||||
to_call: (jam - 1.0).min(stack),
|
||||
hero_stack: stack,
|
||||
min_raise_to: None,
|
||||
max_raise_to: None,
|
||||
legal: vec![ActionKind::Fold, ActionKind::Call],
|
||||
allowed_sizes: None,
|
||||
villains: vec![
|
||||
Villain { seat: 1, stack: 0.5, folded: true, profile: None },
|
||||
Villain { seat: 3, stack: 0.0, folded: false, profile: None },
|
||||
Villain { seat: 4, stack: 100.0, folded: true, profile: None },
|
||||
Villain { seat: 5, stack: 100.0, folded: true, profile: None },
|
||||
Villain { seat: 6, stack: 100.0, folded: true, profile: None },
|
||||
],
|
||||
seed: 11,
|
||||
history: vec![
|
||||
rec(Street::Preflop, 1, SeenAction::PostSmallBlind, Some(0.5)),
|
||||
rec(Street::Preflop, 2, SeenAction::PostBigBlind, Some(1.0)),
|
||||
rec(Street::Preflop, 3, SeenAction::AllIn, Some(jam)),
|
||||
rec(Street::Preflop, 4, SeenAction::Fold, None),
|
||||
rec(Street::Preflop, 5, SeenAction::Fold, None),
|
||||
rec(Street::Preflop, 6, SeenAction::Fold, None),
|
||||
rec(Street::Preflop, 1, SeenAction::Fold, None),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_folding_to_a_jam_lose_and_calling_loses_nothing() {
|
||||
let spot = facing_open_jam("Ac Ad", 20.0, 99.0);
|
||||
let fold = audit_preflop(&spot, Taken::Fold).expect("priced");
|
||||
let call = audit_preflop(&spot, Taken::Call).expect("priced");
|
||||
assert_eq!(fold.method, "jam_preis");
|
||||
assert!(fold.loss > 5.0, "folding aces to a 20 bb jam is expensive, got {}", fold.loss);
|
||||
assert!(call.loss < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calling_a_jam_with_trash_loses_folding_does_not() {
|
||||
let spot = facing_open_jam("7c 2d", 20.0, 99.0);
|
||||
let call = audit_preflop(&spot, Taken::Call).expect("priced");
|
||||
assert!(call.loss > 3.0, "72o calling a 20 bb jam loses, got {}", call.loss);
|
||||
assert!(audit_preflop(&spot, Taken::Fold).unwrap().loss < 1e-9);
|
||||
}
|
||||
|
||||
fn first_in_sb(hero: &str, stack: f64) -> Spot {
|
||||
Spot {
|
||||
variant: Variant::Nlhe,
|
||||
big_blind: 1.0,
|
||||
seats: 2,
|
||||
hero_seat: 1,
|
||||
button_seat: Some(1),
|
||||
hero_cards: Card::parse_list(hero).unwrap(),
|
||||
board: Vec::new(),
|
||||
street: Street::Preflop,
|
||||
pot: 1.5,
|
||||
to_call: 0.5,
|
||||
hero_stack: stack - 0.5,
|
||||
min_raise_to: Some(2.0),
|
||||
max_raise_to: Some(stack),
|
||||
legal: vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise],
|
||||
allowed_sizes: None,
|
||||
villains: vec![Villain { seat: 2, stack: stack - 1.0, folded: false, profile: None }],
|
||||
seed: 3,
|
||||
history: vec![
|
||||
rec(Street::Preflop, 1, SeenAction::PostSmallBlind, Some(0.5)),
|
||||
rec(Street::Preflop, 2, SeenAction::PostBigBlind, Some(1.0)),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_stack_push_fold_prices_the_chart() {
|
||||
let aces = first_in_sb("Ah As", 10.0);
|
||||
assert!(audit_preflop(&aces, Taken::Fold).unwrap().loss > 1.0, "folding aces first in at 10 bb");
|
||||
assert!(audit_preflop(&aces, Taken::Aggress(10.0)).unwrap().loss < 1e-9);
|
||||
let open = audit_preflop(&aces, Taken::Aggress(2.0));
|
||||
assert!(matches!(open, Err(Skip::NotCovered(_))), "a min-raise is no push/fold decision");
|
||||
let deep = first_in_sb("Ah As", 100.0);
|
||||
assert!(matches!(audit_preflop(&deep, Taken::Fold), Err(Skip::NotCovered(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_equity_of_a_made_hand_on_the_flop() {
|
||||
let hero = Card::parse_list("Ac Ad").unwrap();
|
||||
let board = Card::parse_list("Ah 7c 2d").unwrap();
|
||||
let worse = vec![(Card::parse_list("Kc Kd").unwrap(), 1.0)];
|
||||
let e = equity_vs_list(&hero, &board, &worse).unwrap();
|
||||
assert!(e > 0.98 && e < 1.0, "set over an underpair, got {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flop_without_an_all_in_is_skipped() {
|
||||
let mut s = first_in_sb("Ah As", 100.0);
|
||||
s.street = Street::Flop;
|
||||
s.board = Card::parse_list("Kh 7c 2d").unwrap();
|
||||
s.to_call = 3.0;
|
||||
assert!(matches!(audit_flop(&s, Taken::Call), Err(Skip::NotCovered(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Decision audit (plan D4) on the turn: re-solve a real heads-up turn decision with the turn+river
|
||||
//! game over real combos (`cfr::turn_river_game`, the E3 solver) and price the action taken.
|
||||
//!
|
||||
//! Same definitions as the river audit (`engine::audit`): the EV of an action is hero's expected
|
||||
//! chips after taking it at the node and playing the solved strategy afterwards, against the solved
|
||||
//! villain, whose range is conditioned on the observed turn line; the loss is `EV(best) - EV(taken)`.
|
||||
//! The scale is the game's: chips from the start of the turn, each player counted as having put
|
||||
//! `pot / 2` in. Only differences between actions mean anything.
|
||||
//!
|
||||
//! Ranges as on the river: the blueprint where it knows the spot (`$GRUNDSTRATEGIE`, scenario S1),
|
||||
//! else the engine's range model for both players. Hero's real hand is always in the game (added at
|
||||
//! the mean weight when the model would not have played it, flagged `hero_in_range = false`).
|
||||
//!
|
||||
//! Named approximations (all in `Opts`): at most `turn_combos` combos per player (the heaviest; equal
|
||||
//! weights are thinned by a fixed hash, not by card order, so the sample is not biased towards a
|
||||
//! suit or rank); `turn_cards` river cards evenly strided, each standing for its share; the bet menu
|
||||
//! of `TrBets::standard` plus the size played; `turn_iters` CFR+ iterations; no river raise.
|
||||
|
||||
use crate::card::Card;
|
||||
use crate::cfr::river_game::Act;
|
||||
use crate::cfr::turn_river_game::{build, Hands, TNode, TrBets, TrSolver};
|
||||
use crate::engine::audit::{ranges, ActEv, Audit, Opts, Skip, Taken};
|
||||
use crate::engine::turn_game::turn_line;
|
||||
use crate::game::{Spot, Street};
|
||||
use crate::hand::fast7;
|
||||
|
||||
/// A deterministic shuffle key: ties in weight are broken by this, not by the card mask.
|
||||
fn mix(m: u64) -> u64 {
|
||||
let mut x = m.wrapping_mul(0x9E37_79B9_7F4A_7C15);
|
||||
x ^= x >> 31;
|
||||
x.wrapping_mul(0xBF58_476D_1CE4_E5B9)
|
||||
}
|
||||
|
||||
/// Masks and weights of a combo list: off the board, deduplicated, the `max` heaviest (ties by a fixed
|
||||
/// hash), `keep` always in.
|
||||
pub(crate) fn thin(list: &[(Vec<Card>, f64)], board: u64, max: usize, keep: Option<u64>) -> Hands {
|
||||
let mut v: Vec<(u64, f64)> = list
|
||||
.iter()
|
||||
.filter(|(c, w)| c.len() == 2 && *w > 0.0 && w.is_finite())
|
||||
.map(|(c, w)| (fast7::mask(c), *w))
|
||||
.filter(|(m, _)| m & board == 0 && m.count_ones() == 2)
|
||||
.collect();
|
||||
v.sort_by_key(|x| x.0);
|
||||
v.dedup_by_key(|x| x.0);
|
||||
v.sort_by(|a, b| b.1.total_cmp(&a.1).then(mix(a.0).cmp(&mix(b.0))));
|
||||
let kept = keep.and_then(|k| v.iter().find(|x| x.0 == k).map(|x| x.1));
|
||||
v.truncate(max.max(1));
|
||||
if let Some(k) = keep {
|
||||
if !v.iter().any(|x| x.0 == k) {
|
||||
let mean = v.iter().map(|x| x.1).sum::<f64>() / v.len().max(1) as f64;
|
||||
v.push((k, kept.unwrap_or(mean).max(1e-9)));
|
||||
}
|
||||
}
|
||||
Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() }
|
||||
}
|
||||
|
||||
/// Audit one heads-up turn decision.
|
||||
pub fn audit_turn(spot: &Spot, taken: Taken, opts: Opts) -> Result<Audit, Skip> {
|
||||
if spot.street != Street::Turn || spot.board.len() != 4 {
|
||||
return Err(Skip::Street(spot.street));
|
||||
}
|
||||
let gated = crate::engine::read_gate::gate_reads(spot);
|
||||
let spot = &gated;
|
||||
if spot.live_villains().count() != 1 {
|
||||
return Err(Skip::Multiway);
|
||||
}
|
||||
if spot.hero_cards.len() != 2 {
|
||||
return Err(Skip::NoRange("not a two-card hand"));
|
||||
}
|
||||
let villain = spot.live_villains().next().ok_or(Skip::Multiway)?;
|
||||
let (mut hero_list, villain_list, source) = ranges(spot, villain).ok_or(Skip::NoRange("range lists"))?;
|
||||
let held = |c: &Vec<Card>| c.len() == 2 && c.iter().all(|x| spot.hero_cards.contains(x));
|
||||
let hero_in_range = hero_list.iter().any(|(c, _)| held(c));
|
||||
if !hero_in_range {
|
||||
let mean = hero_list.iter().map(|(_, w)| w).sum::<f64>() / hero_list.len().max(1) as f64;
|
||||
hero_list.push((spot.hero_cards.clone(), mean.max(1e-9)));
|
||||
}
|
||||
let (first, line, c) = turn_line(spot, villain);
|
||||
let pot = spot.pot - c[0] - c[1];
|
||||
if pot <= 0.0 {
|
||||
return Err(Skip::NoRange("pot at street start"));
|
||||
}
|
||||
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
|
||||
if stack <= c[0].max(c[1]) + 1e-9 && spot.to_call <= 0.0 {
|
||||
return Err(Skip::NoRange("no stack behind"));
|
||||
}
|
||||
let aggressed = line.iter().any(|a| matches!(a, Act::Bet(_) | Act::Raise(_)));
|
||||
let act = match taken {
|
||||
Taken::Fold if spot.to_call > 0.0 => Act::Fold,
|
||||
Taken::Fold => return Err(Skip::Illegal("fold with nothing to call")),
|
||||
Taken::Check if spot.to_call == 0.0 => Act::Check,
|
||||
Taken::Check => return Err(Skip::Illegal("check facing a bet")),
|
||||
Taken::Call if spot.to_call > 0.0 => Act::Call,
|
||||
Taken::Call => return Err(Skip::Illegal("call with nothing to call")),
|
||||
Taken::Aggress(to) if aggressed => Act::Raise(to.min(stack)),
|
||||
Taken::Aggress(to) => Act::Bet(to.min(stack)),
|
||||
};
|
||||
let aggressive = matches!(act, Act::Bet(_) | Act::Raise(_));
|
||||
let mut forced = line.clone();
|
||||
if aggressive {
|
||||
forced.push(act);
|
||||
}
|
||||
let board = fast7::mask(&spot.board);
|
||||
let hero_mask = fast7::mask(&spot.hero_cards);
|
||||
if hero_mask & board != 0 {
|
||||
return Err(Skip::NoRange("hero cards on the board"));
|
||||
}
|
||||
let hands = [thin(&hero_list, board, opts.turn_combos, Some(hero_mask)), thin(&villain_list, board, opts.turn_combos, None)];
|
||||
if hands[1].masks.is_empty() {
|
||||
return Err(Skip::NoRange("villain range empty"));
|
||||
}
|
||||
let hand = hands[0].masks.iter().position(|m| *m == hero_mask).ok_or(Skip::NoRange("hero hand"))?;
|
||||
let combos = [hands[0].masks.len(), hands[1].masks.len()];
|
||||
let mut bets = TrBets::standard(pot, stack, first);
|
||||
bets.river.max_raises = 0;
|
||||
let game = build(&bets, &forced);
|
||||
let at = game.at.ok_or(Skip::LineLeftTree)?;
|
||||
let hero_node = if aggressive {
|
||||
(0..game.nodes.len())
|
||||
.find(|&i| matches!(&game.nodes[i], TNode::Dec { kids, .. } if kids.contains(&at)))
|
||||
.ok_or(Skip::LineLeftTree)?
|
||||
} else {
|
||||
at
|
||||
};
|
||||
if !matches!(game.nodes.get(hero_node), Some(TNode::Dec { player: 0, street: 0, .. })) {
|
||||
return Err(Skip::LineLeftTree);
|
||||
}
|
||||
let acts = game.acts[hero_node].clone();
|
||||
let nodes = game.nodes.len();
|
||||
let mut solver = TrSolver::new(game, hands, board, Some(opts.turn_cards.max(1)));
|
||||
solver.run(opts.turn_iters.max(1));
|
||||
let strategy = solver.strategy();
|
||||
let exploit = solver.exploitability(&strategy).total;
|
||||
let (values, off_line) = solver.hand_action_values(&strategy, hero_node, hand).ok_or(Skip::NoRange("hero class has no deals"))?;
|
||||
let mix_row = strategy.row(hero_node, 0, hand).to_vec();
|
||||
let list: Vec<ActEv> = acts
|
||||
.iter()
|
||||
.zip(&values)
|
||||
.enumerate()
|
||||
.map(|(k, (a, ev))| ActEv { act: *a, prob: mix_row.get(k).copied().unwrap_or(0.0), ev: *ev })
|
||||
.collect();
|
||||
let mut taken_ix = None;
|
||||
let mut size_gap = 0.0;
|
||||
for (k, ae) in list.iter().enumerate() {
|
||||
match (ae.act, act) {
|
||||
(Act::Bet(x), Act::Bet(y)) | (Act::Raise(x), Act::Raise(y)) => {
|
||||
let gap = (x - y).abs() / x.max(y).max(1e-9);
|
||||
if taken_ix.is_none() || gap < size_gap {
|
||||
taken_ix = Some(k);
|
||||
size_gap = gap;
|
||||
}
|
||||
}
|
||||
(a, t) if a == t => {
|
||||
taken_ix = Some(k);
|
||||
size_gap = 0.0;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let taken_ix = taken_ix.ok_or(Skip::LineLeftTree)?;
|
||||
let ev_best = list.iter().map(|a| a.ev).fold(f64::NEG_INFINITY, f64::max);
|
||||
let ev_mix: f64 = list.iter().map(|a| a.prob * a.ev).sum();
|
||||
let ev_taken = list[taken_ix].ev;
|
||||
Ok(Audit {
|
||||
source,
|
||||
class: hand,
|
||||
classes: combos[0],
|
||||
nodes,
|
||||
first,
|
||||
acts: list,
|
||||
taken: taken_ix,
|
||||
size_gap,
|
||||
ev_best,
|
||||
ev_mix,
|
||||
ev_taken,
|
||||
loss: (ev_best - ev_taken).max(0.0),
|
||||
off_line,
|
||||
hero_in_range,
|
||||
exploitability: exploit,
|
||||
method: "turn_river_game",
|
||||
note: format!("{}x{} combos, {} river cards, {} iterations", combos[0], combos[1], opts.turn_cards, opts.turn_iters),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::game::{ActionKind, Villain};
|
||||
use crate::variant::Variant;
|
||||
|
||||
fn turn_spot(board: &str, hero: &str, pot: f64, to_call: f64, stack: f64) -> Spot {
|
||||
Spot {
|
||||
variant: Variant::Nlhe,
|
||||
big_blind: 1.0,
|
||||
seats: 2,
|
||||
hero_seat: 1,
|
||||
button_seat: Some(1),
|
||||
hero_cards: Card::parse_list(hero).unwrap(),
|
||||
board: Card::parse_list(board).unwrap(),
|
||||
street: Street::Turn,
|
||||
pot,
|
||||
to_call,
|
||||
hero_stack: stack,
|
||||
min_raise_to: Some((2.0 * to_call).max(1.0).min(stack)),
|
||||
max_raise_to: Some(stack),
|
||||
legal: if to_call > 0.0 {
|
||||
vec![ActionKind::Fold, ActionKind::Call, ActionKind::Raise]
|
||||
} else {
|
||||
vec![ActionKind::Check, ActionKind::Raise]
|
||||
},
|
||||
allowed_sizes: None,
|
||||
villains: vec![Villain { seat: 2, stack, folded: false, profile: None }],
|
||||
seed: 7,
|
||||
history: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn quick() -> Opts {
|
||||
Opts { turn_iters: 60, turn_combos: 60, turn_cards: 6, ..Opts::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_the_nut_flush_to_a_turn_bet_loses_calling_does_not() {
|
||||
// Hero holds the nut flush; the villain bets the pot (20 into 20: the pot shows 40).
|
||||
let mut spot = turn_spot("Kh 7h 2h 9c", "Ah Qh", 40.0, 20.0, 100.0);
|
||||
spot.history = vec![crate::game::ActionRecord { street: Street::Turn, seat: 2, action: crate::game::SeenAction::Bet, amount: Some(20.0) }];
|
||||
let fold = audit_turn(&spot, Taken::Fold, quick()).expect("auditable");
|
||||
let call = audit_turn(&spot, Taken::Call, quick()).expect("auditable");
|
||||
assert_eq!(fold.method, "turn_river_game");
|
||||
assert!(fold.loss > 5.0, "folding the nuts must cost real EV, got {}", fold.loss);
|
||||
assert!(call.loss < fold.loss, "calling loses less than folding ({} vs {})", call.loss, fold.loss);
|
||||
assert_eq!(fold.acts[fold.taken].act, Act::Fold);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_played_bet_size_is_priced_exactly() {
|
||||
let spot = turn_spot("Kh 7h 2h 9c", "Ah Qh", 20.0, 0.0, 100.0);
|
||||
let bet = audit_turn(&spot, Taken::Aggress(13.0), quick()).expect("auditable");
|
||||
assert!(bet.size_gap < 1e-9, "size in the tree, gap {}", bet.size_gap);
|
||||
assert!(matches!(bet.acts[bet.taken].act, Act::Bet(x) if (x - 13.0).abs() < 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thinning_keeps_the_hero_hand_and_does_not_follow_card_order() {
|
||||
let all: Vec<(Vec<Card>, f64)> = ["As Ks", "Ad Kd", "Ac Kc", "Ah Kh", "2c 2d", "3c 3d", "4c 4d", "5c 5d"]
|
||||
.iter()
|
||||
.map(|s| (Card::parse_list(s).unwrap(), 1.0))
|
||||
.collect();
|
||||
let keep = fast7::mask(&Card::parse_list("5c 5d").unwrap());
|
||||
for max in 1..4 {
|
||||
let h = thin(&all, 0, max, Some(keep));
|
||||
assert!(h.masks.contains(&keep), "hero hand kept at max {max}");
|
||||
assert!(h.masks.len() == max || h.masks.len() == max + 1);
|
||||
}
|
||||
let h2 = thin(&all, 0, 3, None);
|
||||
let sorted: Vec<u64> = {
|
||||
let mut v: Vec<u64> = all.iter().map(|(c, _)| fast7::mask(c)).collect();
|
||||
v.sort();
|
||||
v.truncate(3);
|
||||
v
|
||||
};
|
||||
assert_ne!(h2.masks, sorted, "equal weights are thinned by hash, not by mask order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiway_and_river_are_not_audited_here() {
|
||||
let mut spot = turn_spot("Kh 7h 2h 9c", "Ah Qh", 20.0, 20.0, 100.0);
|
||||
spot.villains.push(Villain { seat: 3, stack: 100.0, folded: false, profile: None });
|
||||
assert_eq!(audit_turn(&spot, Taken::Call, quick()), Err(Skip::Multiway));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Engine: composes assessment and choice into a decision.
|
||||
|
||||
pub mod audit;
|
||||
pub mod audit_allin;
|
||||
pub mod audit_turn;
|
||||
pub mod bluff;
|
||||
pub mod called;
|
||||
pub mod called_equity;
|
||||
|
||||
@@ -120,7 +120,7 @@ pub struct TurnSolved {
|
||||
|
||||
/// The turn line so far for hero and `villain`: who acted first (0 = hero), the forced actions and the
|
||||
/// street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history.
|
||||
fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
|
||||
pub(crate) fn turn_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
|
||||
let mut first = None;
|
||||
let mut acts = Vec::new();
|
||||
let mut c = [0.0f64, 0.0];
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Spezifikation lesen/audit_lauf.py, betrieb/audit_haken.py, sicht/audit_seite.py (Plan D4) - ohne Client.
|
||||
|
||||
Geprüft wird: aus dem Schatten-Log je Entscheidung die letzte geklickte Anfrage (Enthaltungen und nie
|
||||
geklickte zählen als ausgelassen), die gespielte Aktion im Format der Bin, der Cache (nur Neues geht an
|
||||
die Bin), Summen je Street / Messlatte / Engine-Teil, die teuersten Spots, die Wochensumme aus den
|
||||
Laufberichten, Fixture-Vorschläge (nur neue teure Spots, im Format der Live-Fixture), der ganze Ablauf
|
||||
auf der Platte mit einer Ersatz-Bin, der Haken (abgekoppelt, Idle, abschaltbar, wirft nie) und die
|
||||
Cockpit-Endpunkte. Der Rechner selbst (Rust, engine::audit*) hat eigene Tests; ein Ende-zu-Ende-Test
|
||||
läuft nur, wenn die Bin gebaut ist.
|
||||
|
||||
Öffnet keine Tischfenster: einzeln laufen lassen.
|
||||
|
||||
python tests/audit_lauf_spec.py -v
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
_w = os.path.dirname(os.path.abspath(__file__))
|
||||
while _w != os.path.dirname(_w) and not os.path.isdir(os.path.join(_w, "lesen")):
|
||||
_w = os.path.dirname(_w)
|
||||
for _d in ("lesen", "betrieb", "sicht"):
|
||||
if os.path.join(_w, _d) not in sys.path:
|
||||
sys.path.append(os.path.join(_w, _d))
|
||||
import audit_lauf # noqa: E402
|
||||
import audit_haken # noqa: E402
|
||||
|
||||
C = lambda r, s: {"rank": r, "suit": s} # noqa: E731
|
||||
|
||||
|
||||
def anfrage(street="RIVER", to_call=0.2, pot=1.0, **kw):
|
||||
a = {"variant": "NLHE", "bigBlind": 0.02, "seats": 2, "heroSeat": 1, "street": street,
|
||||
"heroCards": [C("ACE", "SPADES"), C("KING", "SPADES")],
|
||||
"board": {"FLOP": [C("TWO", "HEARTS"), C("SEVEN", "CLUBS"), C("NINE", "DIAMONDS")],
|
||||
"TURN": [C("JACK", "CLUBS")], "RIVER": [C("THREE", "SPADES")]},
|
||||
"pot": pot, "toCall": to_call, "heroStack": 2.0, "maxRaiseTo": 2.0,
|
||||
"legalActions": ["FOLD", "CALL", "RAISE"] if to_call else ["CHECK", "RAISE"],
|
||||
"villains": [{"seat": 2, "stack": 2.0, "folded": False}], "history": [], "_sitze": {"1": 3, "2": 5}}
|
||||
a.update(kw)
|
||||
return a
|
||||
|
||||
|
||||
def eintrag(hand="111", street="RIVER", aktion="CALL", geklickt="kanal call", zeit="2026-11-14 18:00:00",
|
||||
pid=4711, grund="MDF-Boden: Made-Hand verteidigt", size=None, **kw):
|
||||
a = anfrage(street=street, **kw)
|
||||
return {"zeit": zeit, "pid": pid, "raum": "R1", "zug": f"R1|{hand}|{street}|{a['pot']}|{a['toCall']}|x|()",
|
||||
"anfrage": a, "antwort": {"action": aktion, "size": size, "reason": grund}, "geklickt": geklickt}
|
||||
|
||||
|
||||
def ergebnis(loss_bb, method="river_game", taken=1):
|
||||
return {"status": "ok", "source": "modell", "taken": taken, "method": method, "note": "",
|
||||
"acts": [{"act": "Fold", "p": 0.9, "ev": 0.0}, {"act": "Call", "p": 0.1, "ev": -loss_bb * 0.02}],
|
||||
"loss": loss_bb * 0.02, "loss_bb": loss_bb, "bb": 0.02}
|
||||
|
||||
|
||||
class Auswahl(unittest.TestCase):
|
||||
def test_letzte_geklickte_anfrage_je_zug_enthaltung_und_ungeklickt_ausgelassen(self):
|
||||
s = [eintrag(geklickt=None), eintrag(), eintrag(hand="222", geklickt=None),
|
||||
{"zeit": "2026-11-14 18:00:01", "pid": 4711, "zug": "R1|333|RIVER",
|
||||
"anfrage": {"legalActions": [], "_unklar": True}, "antwort": {}, "geklickt": None}]
|
||||
out, aus = audit_lauf.entscheidungen(s)
|
||||
self.assertEqual(len(out), 1)
|
||||
self.assertEqual(out[0]["taken"], {"action": "CALL"})
|
||||
self.assertEqual(aus["nicht geklickt"], 1)
|
||||
self.assertEqual(aus["Enthaltung (Übersetzung)"], 1)
|
||||
|
||||
def test_raise_traegt_den_betrag_sonst_den_hoechsten(self):
|
||||
a = anfrage()
|
||||
self.assertEqual(audit_lauf.genommen(a, {"action": "RAISE", "size": 0.6}), {"action": "RAISE", "amount": 0.6})
|
||||
self.assertEqual(audit_lauf.genommen(a, {"action": "ALL_IN", "size": None}), {"action": "ALL_IN", "amount": 2.0})
|
||||
self.assertIsNone(audit_lauf.genommen(a, {"action": "WARTEN"}))
|
||||
|
||||
def test_karten_und_hand_id(self):
|
||||
e = eintrag(hand="177599600037")
|
||||
self.assertEqual(audit_lauf.hand_id(e), "177599600037")
|
||||
self.assertEqual(audit_lauf.brett(e["anfrage"]), ["2h", "7c", "9d", "Jc", "3s"])
|
||||
|
||||
|
||||
class Rechnen(unittest.TestCase):
|
||||
def test_cache_schickt_nur_neues_an_die_bin_und_ohne_unterstrich_felder(self):
|
||||
gesehen = []
|
||||
|
||||
def rechner(zeilen):
|
||||
gesehen.extend(zeilen)
|
||||
return [ergebnis(1.0) for _ in zeilen]
|
||||
out, _ = audit_lauf.entscheidungen([eintrag(hand="1"), eintrag(hand="2")])
|
||||
cache = {}
|
||||
audit_lauf.rechne(out, rechner, audit_lauf.OPTS_STANDARD, cache)
|
||||
self.assertEqual(len(gesehen), 2)
|
||||
self.assertNotIn("_sitze", gesehen[0])
|
||||
self.assertEqual(gesehen[0]["taken"], {"action": "CALL"})
|
||||
out3, _ = audit_lauf.entscheidungen([eintrag(hand="1"), eintrag(hand="2"), eintrag(hand="3", pot=1.2)])
|
||||
r = audit_lauf.rechne(out3, rechner, audit_lauf.OPTS_STANDARD, cache)
|
||||
self.assertEqual(len(gesehen), 3, "nur die neue Entscheidung geht an die Bin")
|
||||
self.assertEqual(len(r), 3)
|
||||
|
||||
|
||||
def bericht_aus(paare, haende=100):
|
||||
out, aus = audit_lauf.entscheidungen([p[0] for p in paare])
|
||||
daten = [audit_lauf.datensatz(d, er, {}) for d, er in zip(out, [p[1] for p in paare])]
|
||||
return audit_lauf.auswerten(daten, {"pid": 4711, "von": "2026-11-14 18:00:00", "bis": "2026-11-14 19:00:00"}, aus, haende), daten
|
||||
|
||||
|
||||
class Auswerten(unittest.TestCase):
|
||||
def test_summen_je_street_methode_und_engine_teil(self):
|
||||
b, _ = bericht_aus([
|
||||
(eintrag(hand="1"), ergebnis(4.0)),
|
||||
(eintrag(hand="2", street="TURN", grund="top pair"), ergebnis(1.0, "turn_river_game")),
|
||||
(eintrag(hand="3", street="FLOP", grund="top pair"), {"status": "skip", "reason": "not covered: flop"}),
|
||||
])
|
||||
self.assertEqual(b["streets"]["GESAMT"]["n"], 3)
|
||||
self.assertEqual(b["streets"]["GESAMT"]["bewertet"], 2)
|
||||
self.assertAlmostEqual(b["streets"]["GESAMT"]["verlust_bb"], 5.0)
|
||||
self.assertAlmostEqual(b["streets"]["RIVER"]["verlust_bb"], 4.0)
|
||||
self.assertEqual(b["methoden"]["turn_river_game"]["bewertet"], 1)
|
||||
self.assertAlmostEqual(b["wer"]["mdf"]["verlust_bb"], 4.0)
|
||||
self.assertEqual(b["auslass_je_street"]["FLOP"], {"not covered: flop": 1})
|
||||
self.assertEqual(b["top"][0]["hand"], "1")
|
||||
md = audit_lauf.markdown(b)
|
||||
self.assertIn("Die 10 teuersten", md)
|
||||
self.assertIn("MDF-Boden", md)
|
||||
self.assertIn("5.00", md, "bb/100 = 5 bb auf 100 Hände")
|
||||
|
||||
def test_woche_summiert_laufberichte_nur_dieser_woche(self):
|
||||
b1, _ = bericht_aus([(eintrag(hand="1"), ergebnis(4.0))])
|
||||
b2, _ = bericht_aus([(eintrag(hand="2"), ergebnis(2.0))])
|
||||
b3, _ = bericht_aus([(eintrag(hand="3"), ergebnis(9.0))])
|
||||
b3["lauf"]["von"] = "2026-11-24 10:00:00" # andere Woche
|
||||
w = audit_lauf.woche_summe([b1, b2, b3], audit_lauf.iso_woche("2026-11-14"))
|
||||
self.assertEqual(w["woche"], "2026-W46")
|
||||
self.assertAlmostEqual(w["streets"]["GESAMT"]["verlust_bb"], 6.0)
|
||||
self.assertEqual(w["haende"], 200)
|
||||
self.assertEqual([t["hand"] for t in w["top"]], ["1", "2"])
|
||||
|
||||
|
||||
class Fixture(unittest.TestCase):
|
||||
def test_nur_neue_teure_spots_im_format_der_live_fixture(self):
|
||||
_, daten = bericht_aus([(eintrag(hand="1"), ergebnis(4.0)), (eintrag(hand="2"), ergebnis(9.0)),
|
||||
(eintrag(hand="3"), ergebnis(0.5))])
|
||||
neu = audit_lauf.fixture_vorschlaege(daten, {("2", "RIVER")}, schwelle=3.0)
|
||||
self.assertEqual([z["hand"] for z in neu], ["1"])
|
||||
z = neu[0]
|
||||
for k in ("hand", "art", "live", "live_grund", "ergebnis_bb", "spot", "audit"):
|
||||
self.assertIn(k, z)
|
||||
self.assertEqual(z["live"], "CALL")
|
||||
self.assertEqual(z["art"], "audit_river_mdf")
|
||||
self.assertEqual(z["spot"]["street"], "RIVER")
|
||||
|
||||
|
||||
class Platte(unittest.TestCase):
|
||||
"""Der ganze Ablauf mit einer Ersatz-Bin (Python-Skript, das je Zeile 2 bb Verlust meldet)."""
|
||||
|
||||
def setUp(self):
|
||||
self.t = tempfile.mkdtemp(prefix="audit_lauf_spec_")
|
||||
os.makedirs(os.path.join(self.t, "betrieb", "scratch"))
|
||||
os.makedirs(os.path.join(self.t, "archiv", "lauf"))
|
||||
with open(os.path.join(self.t, "betrieb", "scratch", "shadow.jsonl"), "w", encoding="utf-8") as f:
|
||||
for i in range(3):
|
||||
f.write(json.dumps(eintrag(hand=str(i), zeit=f"2026-11-14 18:00:0{i}")) + "\n")
|
||||
with open(os.path.join(self.t, "archiv", "lauf", "haende.jsonl"), "w", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"hand": "1", "zeit": "2026-11-14T17:00:01Z", "netto": -0.5, "bb": 0.02}) + "\n")
|
||||
ersatz = os.path.join(self.t, "ersatz_bin.py")
|
||||
with open(ersatz, "w", encoding="utf-8") as f:
|
||||
f.write("import sys, json\n"
|
||||
"for z in sys.stdin:\n"
|
||||
" if z.strip():\n"
|
||||
" d = json.loads(z)\n"
|
||||
" print(json.dumps({'id': d['id'], 'status': 'ok', 'source': 'modell', 'taken': 1,"
|
||||
" 'method': 'river_game', 'note': '', 'acts': [{'act': 'Fold', 'p': 1, 'ev': 0},"
|
||||
" {'act': 'Call', 'p': 0, 'ev': -0.04}], 'loss': 0.04, 'loss_bb': 2.0, 'bb': 0.02}))\n")
|
||||
self.ersatz = ersatz
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.t, ignore_errors=True)
|
||||
|
||||
def _rechner(self, binary, opts, env=None):
|
||||
def r(zeilen):
|
||||
import subprocess
|
||||
ein = "".join(json.dumps(dict(z, id=i)) + "\n" for i, z in enumerate(zeilen))
|
||||
p = subprocess.run([sys.executable, self.ersatz], input=ein.encode(), stdout=subprocess.PIPE, check=True)
|
||||
return [json.loads(x) for x in p.stdout.decode().splitlines() if x.strip()]
|
||||
return r
|
||||
|
||||
def test_lauf_bericht_woche_fixture_und_cache(self):
|
||||
alt = audit_lauf.bin_aufruf
|
||||
audit_lauf.bin_aufruf = self._rechner
|
||||
try:
|
||||
b = audit_lauf.lauf_bericht(self.t, pid=4711, binary=self.ersatz, still=True)
|
||||
self.assertNotIn("fehler", b)
|
||||
self.assertAlmostEqual(b["streets"]["GESAMT"]["verlust_bb"], 6.0)
|
||||
o = audit_lauf.ordner(self.t)
|
||||
self.assertTrue(os.path.exists(os.path.join(o, "lauf-4711.md")))
|
||||
self.assertTrue(os.path.exists(os.path.join(o, "kern", audit_lauf.BIN_KOPIE)))
|
||||
self.assertEqual(next(t for t in b["top"] if t["hand"] == "1")["ergebnis_bb"], -25.0)
|
||||
self.assertEqual(b["haende"], 1)
|
||||
vor = os.path.join(self.t, "tests", "live_fixture", "vorschlag", "audit-2026-11-14.jsonl")
|
||||
self.assertEqual(b["fixture"]["neu"], 0, "2 bb liegt unter der Schwelle")
|
||||
b2 = audit_lauf.lauf_bericht(self.t, pid=4711, binary=self.ersatz, still=True, schwelle=1.0)
|
||||
self.assertEqual(b2["fixture"]["neu"], 3)
|
||||
b3 = audit_lauf.lauf_bericht(self.t, pid=4711, binary=self.ersatz, still=True, schwelle=1.0)
|
||||
self.assertEqual(b3["fixture"]["neu"], 0, "ein Spot wird nur einmal vorgeschlagen")
|
||||
with open(vor, encoding="utf-8") as f:
|
||||
self.assertEqual(len(f.readlines()), 3)
|
||||
w = audit_lauf.woche_schreiben(self.t)
|
||||
self.assertEqual(w["woche"], "2026-W46")
|
||||
self.assertTrue(os.path.exists(os.path.join(o, "woche-2026-W46.md")))
|
||||
self.assertEqual(audit_lauf.nach_lauf(self.t, 4711), 0)
|
||||
self.assertEqual(audit_lauf.nach_lauf(self.t, 999), 1, "unbekannter Lauf: Fehler ins Log")
|
||||
with open(os.path.join(o, "fehler.log"), encoding="utf-8") as f:
|
||||
self.assertIn("pid 999", f.read())
|
||||
finally:
|
||||
audit_lauf.bin_aufruf = alt
|
||||
|
||||
def test_cockpit_endpunkte(self):
|
||||
import audit_seite
|
||||
alt = audit_lauf.bin_aufruf
|
||||
audit_lauf.bin_aufruf = self._rechner
|
||||
os.environ["AUDIT_WURZEL"] = self.t
|
||||
try:
|
||||
code, daten, art = audit_seite.antwort("/audit")
|
||||
self.assertEqual(code, 200)
|
||||
self.assertIn(b"Entscheidungs-Audit", daten)
|
||||
r = json.loads(audit_seite.antwort("/api/audit", "pid=4711")[1])
|
||||
self.assertEqual(r["status"], "fehlt")
|
||||
audit_lauf.lauf_bericht(self.t, pid=4711, binary=self.ersatz, still=True)
|
||||
audit_lauf.woche_schreiben(self.t)
|
||||
r = json.loads(audit_seite.antwort("/api/audit", "pid=4711")[1])
|
||||
self.assertEqual(r["status"], "fertig")
|
||||
self.assertAlmostEqual(r["bericht"]["streets"]["GESAMT"]["verlust_bb"], 6.0)
|
||||
r = json.loads(audit_seite.antwort("/api/audit", "")[1])
|
||||
self.assertEqual(r["bericht"]["lauf"]["pid"], 4711)
|
||||
l = json.loads(audit_seite.antwort("/api/audit/laeufe")[1])
|
||||
self.assertEqual([(x["pid"], x["bericht"]) for x in l], [(4711, True)])
|
||||
w = json.loads(audit_seite.antwort("/api/audit/woche")[1])
|
||||
self.assertEqual(w["bericht"]["woche"], "2026-W46")
|
||||
self.assertIsNone(audit_seite.antwort("/sonst"))
|
||||
finally:
|
||||
audit_lauf.bin_aufruf = alt
|
||||
os.environ.pop("AUDIT_WURZEL", None)
|
||||
|
||||
|
||||
class Haken(unittest.TestCase):
|
||||
def test_startet_abgekoppelt_idle_und_kehrt_sofort_zurueck(self):
|
||||
gestartet = []
|
||||
audit_haken.anstossen(pid=4711, wurzel="W", starten=lambda b, **kw: gestartet.append((b, kw)) or "p")
|
||||
(b, kw), = gestartet
|
||||
self.assertEqual(b[-5:], ["--nach-lauf", "--pid", "4711", "--wurzel", "W"])
|
||||
self.assertTrue(b[1].endswith(os.path.join("lesen", "audit_lauf.py")))
|
||||
if sys.platform == "win32":
|
||||
self.assertTrue(kw["creationflags"] & audit_haken.IDLE_PRIORITY_CLASS)
|
||||
self.assertTrue(kw["creationflags"] & audit_haken.DETACHED_PROCESS)
|
||||
|
||||
def test_abschaltbar_und_wirft_nie(self):
|
||||
os.environ["AUDIT_NACH_LAUF"] = "0"
|
||||
try:
|
||||
self.assertIsNone(audit_haken.anstossen(pid=1, starten=lambda *a, **k: 1 / 0))
|
||||
finally:
|
||||
os.environ.pop("AUDIT_NACH_LAUF")
|
||||
|
||||
def kaputt(*a, **k):
|
||||
raise OSError("kein python")
|
||||
self.assertIsNone(audit_haken.anstossen(pid=1, starten=kaputt))
|
||||
|
||||
|
||||
@unittest.skipUnless(audit_lauf.bin_suchen(_w, _w), "audit-Bin nicht gebaut")
|
||||
class EndeZuEnde(unittest.TestCase):
|
||||
def test_echte_bin_rechnet_preflop_turn_river(self):
|
||||
jam = anfrage(street="PREFLOP", to_call=0.39, pot=0.43, board={}, heroCards=[C("SEVEN", "CLUBS"), C("TWO", "DIAMONDS")],
|
||||
seats=6, heroSeat=2, legalActions=["FOLD", "CALL"],
|
||||
villains=[{"seat": 1, "stack": 0.0, "folded": True}, {"seat": 3, "stack": 0.0, "folded": False}],
|
||||
history=[{"street": "PREFLOP", "seat": 1, "action": "POST_SB", "amount": 0.01},
|
||||
{"street": "PREFLOP", "seat": 2, "action": "POST_BB", "amount": 0.02},
|
||||
{"street": "PREFLOP", "seat": 3, "action": "ALL_IN", "amount": 0.4},
|
||||
{"street": "PREFLOP", "seat": 1, "action": "FOLD"}])
|
||||
zeilen = [dict(jam, taken={"action": "CALL"})]
|
||||
binary = audit_lauf.bin_suchen(_w, _w)
|
||||
out = audit_lauf.bin_aufruf(binary, audit_lauf.OPTS_STANDARD)(zeilen)
|
||||
self.assertEqual(out[0]["status"], "ok", out[0])
|
||||
self.assertEqual(out[0]["method"], "jam_preis")
|
||||
self.assertGreater(out[0]["loss_bb"], 1.0, "72o ruft einen 20-bb-Jam: teuer")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user