diff --git a/messung/turnier/startprobe/turniermotor_probe.py b/messung/turnier/startprobe/turniermotor_probe.py new file mode 100644 index 00000000..eb344a6e --- /dev/null +++ b/messung/turnier/startprobe/turniermotor_probe.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Startprobe des Turniermotors auf geloggten Turnieranfragen (archiv/lauf/turniermotor.jsonl): gueltige Zuege, Zeiten, +8er-Tische, Antes, Stapeltiefen. Spricht die Exe wie der Laeufer (eine JSON-Zeile hin, eine zurueck; entscheiden/schatten.py), +mit `blinds_einpassen` und `einpassen` aus entscheiden/turniermotor.py (aus dem Quelltext geladen, ohne den Laeufer zu importieren). + + python turniermotor_probe.py [K=V ...] + +Ergebnis: je Anfrage eine Zeile (nur anhaengen), am Ende eine Zusammenfassung auf stdout. +""" +import ast +import json +import os +import subprocess +import sys +import threading +import time + + +def lade_funktionen(pfad): + """blinds_einpassen und einpassen aus dem Quelltext (ohne Import von schatten/decide).""" + baum = ast.parse(open(pfad, encoding="utf-8").read()) + teile = [n for n in baum.body if isinstance(n, ast.FunctionDef) and n.name in ("blinds_einpassen", "einpassen")] + ns = {} + exec(compile(ast.Module(body=teile, type_ignores=[]), pfad, "exec"), ns) + return ns["blinds_einpassen"], ns["einpassen"] + + +def gueltig(q, r): + """(ok, Grund) fuer eine Antwort nach `einpassen`.""" + if not isinstance(r, dict) or "action" not in r: + return False, "keine Antwort" + a, legal = r["action"], q.get("legalActions") or [] + if a == "ABSTAIN": + return False, "ABSTAIN: " + str(r.get("reason", ""))[:80] + if a not in legal: + return False, f"{a} nicht erlaubt ({legal})" + if a in ("RAISE", "BET"): + s = r.get("size") + lo, hi = q.get("minRaiseTo"), q.get("maxRaiseTo") + if not isinstance(s, (int, float)) or (lo is not None and s < lo - 1e-6) or (hi is not None and s > hi + 1e-6): + return False, f"Groesse {s} ausserhalb [{lo}, {hi}]" + return True, "" + + +def merkmale(q): + hist = q.get("history") or [] + bb = q.get("bigBlind") or 1.0 + held = q.get("heroStack", 0.0) + max([h.get("amount") or 0 for h in hist if h.get("seat") == q.get("heroSeat")] + [0]) + gegner = [v.get("stack", 0.0) for v in q.get("villains") or []] + return {"spieler": len(gegner) + 1, "ante": any(h.get("action") == "POST_ANTE" for h in hist), + "tief_bb": round(held / bb, 1), "strasse": q.get("street")} + + +def main(): + quelle, ein, aus, frist = sys.argv[1], sys.argv[2], sys.argv[3], float(sys.argv[4]) + befehl = json.load(open(sys.argv[5], encoding="utf-8")) if os.path.isfile(sys.argv[5]) else json.loads(sys.argv[5]) + env = dict(os.environ) + env.update(dict(x.split("=", 1) for x in sys.argv[6:])) + blinds_einpassen, einpassen = lade_funktionen(quelle) + kw = {"creationflags": 0x08000000 | 0x4000} if sys.platform == "win32" else {} + fertig = set() + if os.path.exists(aus): + fertig = {json.loads(z)["nr"] for z in open(aus, encoding="utf-8")} + p, neustarts = None, 0 + with open(aus, "a", encoding="utf-8") as f: + for nr, z in enumerate(open(ein, encoding="utf-8")): + e = json.loads(z) + if "q" not in e or nr in fertig: + continue + q = e["q"] if isinstance(e["q"], dict) else json.loads(e["q"]) + q = blinds_einpassen(q) + if p is None or p.poll() is not None: + if p is not None: + neustarts += 1 + p = subprocess.Popen(befehl, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + encoding="utf-8", env=env, **kw) + t0 = time.time() + box = [] + try: + p.stdin.write(json.dumps(dict(q, seed=nr * 7919 + 1, frist_rest_s=frist)) + "\n") + p.stdin.flush() + th = threading.Thread(target=lambda: box.append(p.stdout.readline()), daemon=True) + th.start() + th.join(frist + 60.0) + except OSError: + pass + dauer = time.time() - t0 + roh = box[0] if box else "" + try: + r = einpassen(q, json.loads(roh)) + except Exception: + r = None + ok, grund = gueltig(q, r) + if not box: + p.kill() + grund = "keine Antwort in Frist+60 s" + f.write(json.dumps({"nr": nr, "zeit": e.get("zeit"), "hand": e.get("hand"), **merkmale(q), "s": round(dauer, 3), + "in_frist": dauer <= frist, "ok": ok, "grund": grund, + "zug": {k: (r or {}).get(k) for k in ("action", "size")}, "reason": str((r or {}).get("reason", ""))[:160]}, + ensure_ascii=False) + "\n") + f.flush() + if p is not None and p.poll() is None: + p.kill() + zeilen = [json.loads(z) for z in open(aus, encoding="utf-8")] + def satz(gruppe): + if not gruppe: + return "0" + s = sorted(x["s"] for x in gruppe) + return (f"{len(gruppe)}: gueltig {sum(x['ok'] for x in gruppe)}, in Frist {sum(x['in_frist'] for x in gruppe)}, " + f"p50 {s[len(s) // 2]:.2f} s, p95 {s[int(len(s) * 0.95)]:.2f} s, max {s[-1]:.2f} s") + print("alle", satz(zeilen), "| Neustarts", neustarts) + for name, wahl in (("vorflop", lambda x: x["strasse"] == "PREFLOP"), ("nach dem Flop", lambda x: x["strasse"] != "PREFLOP"), + ("7-8 Spieler", lambda x: x["spieler"] >= 7), ("bis 6 Spieler", lambda x: x["spieler"] <= 6), + ("mit Ante", lambda x: x["ante"]), ("ohne Ante", lambda x: not x["ante"]), + ("unter 7 bb", lambda x: x["tief_bb"] < 7), ("7-80 bb", lambda x: 7 <= x["tief_bb"] <= 80), + ("ueber 80 bb", lambda x: x["tief_bb"] > 80)): + print(f" {name}: {satz([x for x in zeilen if wahl(x)])}") + schlecht = [x for x in zeilen if not x["ok"]] + for x in schlecht[:15]: + print(" ungueltig:", x["nr"], x["strasse"], x["spieler"], x["tief_bb"], x["grund"], x["zug"]) + + +if __name__ == "__main__": + main()