#!/usr/bin/env python3 """Einblick: aus den dauerhaft geloggten eigenen Zuegen (archiv/lauf/zuege.jsonl) die Spielweise der Engine in Zahlen - je Street, je Vorflop-Position, je Postflop-Handklasse, und die Begruendungs- Taxonomie des Kerns. Rein aus dem, was schon geloggt ist (lesen/handreview): kein neues Logging. Anders als betrieb/review.py (Filter-Sucher, listet einzelne Haende) aggregiert dies - der statistische Leak-Finder: "wie oft checkt die Engine welchen Drilling", "wie aggressiv am River", "welche Vorflop-Position spielt zu breit". Mit `arm=` nur die Zuege eines A/B-Arms (Feld "arm", im Lauf per COINPOKER_ARM gesetzt) - so lassen sich die Insights je Arm vergleichen. Reine Funktionen (Platte nur in `laden`/`main`); Spezifikation: tests/einblick_spec.py. python3 lesen/einblick.py [zuege.jsonl] [--arm A] [--tags 20] [--haende haende.jsonl] """ import collections import json import os import sys STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER") # Positionen, wie der Vorflop-Grund des Kerns sie nennt ("MP open", "SB vs limp", "BTN open"). POSITIONEN = {"UTG", "UTG1", "UTG2", "UTG3", "LJ", "HJ", "MP", "MP1", "MP2", "CO", "BTN", "SB", "BB"} AGGRESSIV = {"BET", "RAISE"} def nur_arm(zuege, arm): """Zuege eines A/B-Arms (Feld "arm"). `arm=None` -> alle; sonst exakt dieser Arm.""" if arm is None: return list(zuege) return [z for z in zuege if isinstance(z, dict) and z.get("arm") == arm] def _quote(zaehler, aktionen): n = sum(zaehler.values()) return (sum(zaehler.get(a, 0) for a in aktionen) / n) if n else 0.0 def aktionen_je_street(zuege): """Je Street: Zahl der Zuege, Aktionsverteilung, Aggressiv-Anteil (BET+RAISE), Fold-Anteil.""" je = {s: collections.Counter() for s in STREETS} for z in zuege: if not isinstance(z, dict): continue st, ak = z.get("street"), z.get("aktion") if st in je and ak: je[st][ak] += 1 out = [] for s in STREETS: c = je[s] n = sum(c.values()) if not n: continue out.append({"street": s, "zuege": n, "aktionen": dict(c), "aggressiv": _quote(c, AGGRESSIV), "fold": _quote(c, {"FOLD"})}) return out def position(grund): """Die Vorflop-Position aus dem Grund des Kerns (erstes Token), oder None. "MP open" -> "MP".""" if not grund: return None teile = str(grund).strip().split() return teile[0] if teile and teile[0] in POSITIONEN else None def vorflop_je_position(zuege): """Vorflop je Position (aus dem Grund): Zuege, Aktionsverteilung, Aggressiv-/Fold-Anteil. Die Zuege ohne erkennbare Position fallen weg (kein Rate-Spiel).""" je = collections.defaultdict(collections.Counter) for z in zuege: if not isinstance(z, dict) or z.get("street") != "PREFLOP": continue p = position(z.get("grund")) if p is None or not z.get("aktion"): continue je[p][z["aktion"]] += 1 out = [] for p in sorted(je): c = je[p] out.append({"position": p, "zuege": sum(c.values()), "aktionen": dict(c), "aggressiv": _quote(c, AGGRESSIV), "fold": _quote(c, {"FOLD"})}) return out def klassen_postflop(zuege): """Postflop je Handklasse (Feld "klasse": HighCard/Pair/TwoPair/...): Aktionsverteilung und Aggressiv-Anteil. Das ist der Leak-Finder als Statistik - z. B. der Anteil gecheckter Drillinge.""" je = collections.defaultdict(collections.Counter) for z in zuege: if not isinstance(z, dict) or z.get("street") == "PREFLOP": continue k = z.get("klasse") if not k or not z.get("aktion"): continue je[k][z["aktion"]] += 1 out = [] for k in sorted(je): c = je[k] out.append({"klasse": k, "zuege": sum(c.values()), "aktionen": dict(c), "aggressiv": _quote(c, AGGRESSIV)}) return out def _tag(grund): """Der Begruendungs-Kopf (vor '->', ',' oder ':'): "middle pair on wet board: equity .." -> die Regel ohne die Zahlen. So faltet sich die Taxonomie des Kerns zu zaehlbaren Tags.""" if not grund: return "(leer)" kopf = str(grund).split("->")[0].split(",")[0].split(":")[0].strip() return kopf[:48] if kopf else "(leer)" def grund_tags(zuege, n=15): """Die haeufigsten Begruendungs-Koepfe des Kerns (welche Regel wie oft feuert).""" c = collections.Counter(_tag(z.get("grund")) for z in zuege if isinstance(z, dict)) return [{"tag": t, "n": k} for t, k in c.most_common(n)] def ergebnis_linsen(haende, arm=None): """Ergebnis je A/B-Arm durch drei Linsen: roh, All-in-EV, AIVAT (lesen/aivat: All-in-EV + Kartenglueck je Street heraus, mittelwerttreu). Bereinigt wird ueber alle Haende zusammen, getrennt nach Arm danach. -> Liste {arm, n, roh, allin_ev, aivat} mit je {bb100, halb95}.""" import aivat haende = [h for h in haende if isinstance(h, dict)] def _y(h, ev): if ev and isinstance(h.get("netto_bb_ev"), (int, float)): return float(h["netto_bb_ev"]) if isinstance(h.get("netto"), (int, float)) and isinstance(h.get("bb"), (int, float)) and h["bb"]: return h["netto"] / h["bb"] return None av = aivat.linse(haende, netto=lambda h: _y(h, False)) je = collections.defaultdict(lambda: ([], [], [])) for h, a in zip(haende, av): r, e = _y(h, False), _y(h, True) if r is None: continue g = je[h.get("arm") or "?"] g[0].append(r) g[1].append(e) g[2].append(a) out = [] for name, (r, e, a) in sorted(je.items()): if arm is not None and name != arm: continue out.append({"arm": name, "n": len(r), "roh": aivat.kennzahl(r), "allin_ev": aivat.kennzahl(e), "aivat": aivat.kennzahl(a)}) return out def bericht(zuege, arm=None, tags=15, haende=None): """Der ganze Einblick als JSON-faehiges Dict. Mit `arm` nur die Zuege dieses A/B-Arms; mit `haende` (haende.jsonl) zusaetzlich das Ergebnis je Arm durch die Linsen roh / All-in-EV / AIVAT.""" zuege = nur_arm(zuege, arm) return {"arm": arm, "zuege": len(zuege), "je_street": aktionen_je_street(zuege), "je_position": vorflop_je_position(zuege), "je_klasse": klassen_postflop(zuege), "grund_tags": grund_tags(zuege, tags), "ergebnis": ergebnis_linsen(haende, arm) if haende else []} def _p(x): return f"{x * 100:4.0f} %" def text(b): """Der Einblick als lesbarer Bericht.""" kopf = "=== Einblick: Spielweise aus den Zuegen ===" if b["arm"] is not None: kopf += f" (Arm {b['arm']})" z = [kopf, f"Zuege: {b['zuege']}", ""] z.append("je Street Zuege aggressiv fold") for r in b["je_street"]: z.append(f" {r['street']:<12} {r['zuege']:>5} {_p(r['aggressiv'])} {_p(r['fold'])}") if b["je_position"]: z += ["", "Vorflop je Position Zuege aggressiv fold"] for r in b["je_position"]: z.append(f" {r['position']:<17} {r['zuege']:>5} {_p(r['aggressiv'])} {_p(r['fold'])}") if b["je_klasse"]: z += ["", "Postflop je Handklasse Zuege aggressiv (Aktionen)"] for r in b["je_klasse"]: akt = " ".join(f"{k}:{v}" for k, v in sorted(r["aktionen"].items())) z.append(f" {r['klasse']:<19} {r['zuege']:>5} {_p(r['aggressiv'])} {akt}") z += ["", "haeufigste Begruendungen des Kerns:"] for r in b["grund_tags"]: z.append(f" {r['n']:>4} {r['tag']}") if b.get("ergebnis"): def _l(k): if k["bb100"] is None or k["halb95"] is None: return "-" return f"{k['bb100']:+7.1f} ±{k['halb95']:5.1f}" z += ["", "Ergebnis je Arm (bb/100, 95 %) roh All-in-EV AIVAT"] for r in b["ergebnis"]: z.append(f" {str(r['arm'])[:28]:<28} n={r['n']:<5} {_l(r['roh'])} {_l(r['allin_ev'])} {_l(r['aivat'])}") return "\n".join(z) + "\n" def laden(pfad): """Zug-Dicts aus einer jsonl-Datei; fehlende/kaputte Datei oder Zeile -> faellt weg.""" out = [] try: with open(pfad, "r", encoding="utf-8", errors="replace") as f: for zeile in f: zeile = zeile.strip() if not zeile: continue try: d = json.loads(zeile) except ValueError: continue if isinstance(d, dict): out.append(d) except OSError: return [] return out def main(argv): pfad = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "archiv", "lauf", "zuege.jsonl") arm, tags, haende_pfad = None, 15, None i = 0 while i < len(argv): if argv[i] == "--haende" and i + 1 < len(argv): haende_pfad = argv[i + 1] i += 2 elif argv[i] == "--arm" and i + 1 < len(argv): arm = argv[i + 1] i += 2 elif argv[i] == "--tags" and i + 1 < len(argv): try: tags = int(argv[i + 1]) except ValueError: pass i += 2 else: pfad = argv[i] i += 1 haende = laden(haende_pfad) if haende_pfad else None print(text(bericht(laden(pfad), arm=arm, tags=tags, haende=haende))) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))