Kern-Anteil nach jedem Lauf: Solver gegen Faustregel je Straße/Lage, Warnung bei Faustregel-Zügen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 15:17:11 +01:00
co-authored by Claude Opus 5.5
parent f47ea569bc
commit 9c05fad918
3 changed files with 153 additions and 4 deletions
+13 -4
View File
@@ -6,7 +6,8 @@ Eingebaut in `betrieb/runner.py`, `live()`, im `finally` neben den anderen Haken
zeit_haken.anstossen()
Schalter `ZEIT_NACH_LAUF=0` schaltet ihn ab. Ausgabe: archiv/audit/zeit-<pid>.md, zeit-gesamt.md,
bei Leck eine Zeile in archiv/audit/zeit-warnung.log.
bei Leck eine Zeile in archiv/audit/zeit-warnung.log. Startet zusätzlich lesen/kern_anteil.py
(archiv/audit/anteil-<pid>.md, bei Faustregel-Zügen eine Zeile in anteil-warnung.log).
"""
import os
import subprocess
@@ -16,15 +17,16 @@ import abgekoppelt # liegt neben diesem Haken in betrieb/
BAUM = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SKRIPT = os.path.join(BAUM, "lesen", "zeit_leck.py")
ANTEIL = os.path.join(BAUM, "lesen", "kern_anteil.py") # Solver-Kern gegen Faustregel, gleicher Haken
IDLE_PRIORITY_CLASS = 0x00000040
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
CREATE_NO_WINDOW = 0x08000000
def befehl(pid, wurzel=BAUM, python=None):
def befehl(pid, wurzel=BAUM, python=None, skript=SKRIPT):
"""Die Kommandozeile der Prüfung für den Lauf `pid`."""
return [python or sys.executable, SKRIPT, "--nach-lauf", "--pid", str(pid), "--wurzel", wurzel]
return [python or sys.executable, skript, "--nach-lauf", "--pid", str(pid), "--wurzel", wurzel]
def anstossen(pid=None, wurzel=BAUM, starten=None):
@@ -41,6 +43,13 @@ def anstossen(pid=None, wurzel=BAUM, starten=None):
else:
kw["start_new_session"] = True
kw["preexec_fn"] = lambda: os.nice(19)
return abgekoppelt.starten(starten or subprocess.Popen, befehl(pid, wurzel), kw)
erster = None
for skript in (SKRIPT, ANTEIL):
try:
p = abgekoppelt.starten(starten or subprocess.Popen, befehl(pid, wurzel, skript=skript), dict(kw))
except Exception: # noqa: BLE001 - die zweite Prüfung startet auch, wenn die erste scheitert
p = None
erster = erster or p
return erster
except Exception: # noqa: BLE001 - eine Prüfung darf das Ende des Läufers nie stören
return None
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Wer hat postflop entschieden? Anteil Solver-Kern gegen Faustregel je Lauf.
Liest die echten Züge aus `betrieb/scratch/shadow*.jsonl`. Ein Zug zählt als Solver, wenn sein Grund
mit `solver-kern` beginnt, sonst als Faustregel. Gezählt je Straße und heads-up/multiway, dazu die
häufigsten Faustregel-Gründe (erste Wörter), damit jede Lücke einen Namen hat.
Ziel: Faustregel-Anteil 0. Jeder Lauf mit Faustregel-Zügen schreibt eine Zeile nach
archiv/audit/anteil-warnung.log.
python3 lesen/kern_anteil.py [--pid N]
python3 lesen/kern_anteil.py --nach-lauf --pid N [--wurzel BAUM]
-> archiv/audit/anteil-<pid>.md
Nur Aggregate, keine Namen.
"""
import argparse
import collections
import glob
import json
import os
import sys
def protokolle(wurzel):
return sorted(glob.glob(os.path.join(wurzel, "betrieb", "scratch", "shadow*.jsonl")))
def grundklasse(grund):
"""Kurzname einer Faustregel: der Text vor dem ersten Doppelpunkt, gekürzt."""
g = str(grund or "").split(":")[0].strip()
return (g[:60] or "(ohne Grund)")
def zug(d, pid=None):
"""-> (strasse, 'hu'|'mw', solver: bool, grund) oder None."""
if not isinstance(d, dict) or (pid is not None and d.get("pid") != pid):
return None
q, a = d.get("anfrage"), d.get("antwort")
if not isinstance(q, dict) or not isinstance(a, dict):
return None
strasse = str(q.get("street") or "").upper()
if strasse in ("", "PREFLOP"):
return None
gegner = [v for v in (q.get("villains") or []) if isinstance(v, dict) and not v.get("folded")]
grund = str(a.get("reason") or "")
return strasse, ("mw" if len(gegner) > 1 else "hu"), grund.startswith("solver-kern"), grund
def zuege(pfade, pid=None):
aus = []
for pfad in pfade:
try:
datei = open(pfad, encoding="utf-8", errors="replace")
except OSError:
continue
with datei:
for zeile in datei:
if '"antwort"' not in zeile:
continue
try:
z = zug(json.loads(zeile), pid)
except ValueError:
continue
if z is not None:
aus.append(z)
return aus
def bericht(zs, titel):
zeilen = [f"# {titel}", "", "Postflop-Entscheidungen: Solver-Kern gegen Faustregel. Ziel: Faustregel 0.", "",
"| Straße | Lage | Züge | Faustregel | Anteil |", "|---|---|---:|---:|---:|"]
zahl = collections.Counter((s, l) for s, l, _, _ in zs)
faust = collections.Counter((s, l) for s, l, solver, _ in zs if not solver)
for s in ("FLOP", "TURN", "RIVER"):
for lage in ("hu", "mw"):
n = zahl[(s, lage)]
if n:
zeilen.append(f"| {s} | {lage} | {n} | {faust[(s, lage)]} | {100 * faust[(s, lage)] / n:.0f} % |")
n, f = len(zs), sum(faust.values())
zeilen.append(f"| alle | | {n} | {f} | {100 * f / n if n else 0:.0f} % |")
gruende = collections.Counter(grundklasse(g) for _, _, solver, g in zs if not solver)
if gruende:
zeilen += ["", "Häufigste Faustregel-Gründe:", ""]
zeilen += [f"- {k} ({v})" for k, v in gruende.most_common(10)]
return "\n".join(zeilen) + "\n", {"zuege": n, "faustregel": f}
def nach_lauf(pid, wurzel):
ordner = os.path.join(wurzel, "archiv", "audit")
os.makedirs(ordner, exist_ok=True)
text, z = bericht(zuege(protokolle(wurzel), pid), f"Kern-Anteil Lauf {pid}")
with open(os.path.join(ordner, f"anteil-{pid}.md"), "w", encoding="utf-8", newline="\n") as f:
f.write(text)
if z["faustregel"]:
with open(os.path.join(ordner, "anteil-warnung.log"), "a", encoding="utf-8", newline="\n") as f:
f.write(f"Lauf {pid}: Faustregel {z['faustregel']} von {z['zuege']} Postflop-Zügen "
f"({100 * z['faustregel'] / z['zuege']:.0f} %)\n")
return z
def main(argv=None):
p = argparse.ArgumentParser(description="Anteil Solver-Kern gegen Faustregel")
p.add_argument("--nach-lauf", action="store_true")
p.add_argument("--pid", type=int)
p.add_argument("--wurzel", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
a = p.parse_args(argv)
if a.nach_lauf:
if a.pid is None:
p.error("--nach-lauf braucht --pid")
nach_lauf(a.pid, a.wurzel)
return 0
text, _ = bericht(zuege(protokolle(a.wurzel), a.pid), "Kern-Anteil")
sys.stdout.write(text)
return 0
if __name__ == "__main__":
sys.exit(main())
+22
View File
@@ -12,6 +12,7 @@ for _u in ("lesen", "betrieb"):
import zeit_leck # noqa: E402
import zeit_haken # noqa: E402
import kern_anteil # noqa: E402
def zeile(kat, zeit, strasse="FLOP", to_call=0.0, pot=0.1, pid=7, aktion="BET"):
@@ -91,12 +92,33 @@ def test_haken_abschaltbar_und_wirft_nie():
gerufen = []
zeit_haken.anstossen(pid=5, starten=lambda cmd, **kw: gerufen.append(cmd) or "p")
assert gerufen and gerufen[0][gerufen[0].index("--pid") + 1] == "5", gerufen
assert len(gerufen) == 2 and gerufen[1][1].endswith("kern_anteil.py"), gerufen
def kaputt(*a, **k):
raise OSError("nein")
assert zeit_haken.anstossen(pid=5, starten=kaputt) is None
def kern_zeile(street, grund, gegner=1, pid=7):
return {"pid": pid, "anfrage": {"street": street, "villains": [{"seat": i} for i in range(gegner)]},
"antwort": {"action": "CHECK", "reason": grund}}
def test_kern_anteil_zaehlt_und_warnt():
zs = [kern_zeile("FLOP", "solver-kern flop+turn ..."), kern_zeile("FLOP", "air on dry board: x", gegner=2),
kern_zeile("RIVER", "top pair good kicker: equity 0.00"), kern_zeile("PREFLOP", "CO open")]
with tempfile.TemporaryDirectory() as d:
schreiben(d, zs)
z = kern_anteil.nach_lauf(7, d)
assert z == {"zuege": 3, "faustregel": 2}, z
audit = os.path.join(d, "archiv", "audit")
with open(os.path.join(audit, "anteil-7.md"), encoding="utf-8") as f:
t = f.read()
assert "| FLOP | mw | 1 | 1 | 100 % |" in t and "top pair good kicker (1)" in t, t
with open(os.path.join(audit, "anteil-warnung.log"), encoding="utf-8") as f:
assert "Faustregel 2 von 3" in f.read()
if __name__ == "__main__":
fehler = 0
for name, f in sorted(globals().items()):