From 741c983512d90ceecbdcf7c6b88f2d3b0d80b983 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 04:53:57 +0100 Subject: [PATCH] vorflop_selbst: real VSELBS02 sidecar reader, archive list from the motor rows (TSV on the SSD, sums only in the repo), direction per decision, spec Co-Authored-By: Claude Opus 5.5 --- .../innovation/vorflop_selbst/auswertung.py | 98 ++++++++++++++++ messung/innovation/vorflop_selbst/sidecar.py | 80 ++++++++----- .../vorflop_selbst/vorflop_selbst.py | 95 +++++---------- messung/innovation/vorflop_selbst/wert.py | 28 +++++ tests/innovation_vorflop_selbst_spec.py | 108 ++++++++++++++++++ 5 files changed, 316 insertions(+), 93 deletions(-) create mode 100644 messung/innovation/vorflop_selbst/auswertung.py diff --git a/messung/innovation/vorflop_selbst/auswertung.py b/messung/innovation/vorflop_selbst/auswertung.py new file mode 100644 index 00000000..cb4ee1a7 --- /dev/null +++ b/messung/innovation/vorflop_selbst/auswertung.py @@ -0,0 +1,98 @@ +"""Archive list of the self-consistency sidecar: rows per changed decision, TSV, summary numbers (pure, no I/O). + +Input: rows of `vorflop-selbst-archiv` (changed decisions: key, class, action names, roles, pi_alt, pi_neu, values V with covariance, R, R_se, w, reach, played move, +line index `i`) and the archive description per line index (`entscheidungen.jsonl`: pos, linie, spieler, sonder). Output carries no player or hand IDs, no line indices. +""" +import collections + +import wert as W + +SPALTEN = ["linie", "position", "spieler", "sonder", "knoten", "klasse", "gespielt", "alt", "neu", "richtung", "R", "R_se", "R_untere95", "w", "erreichbarkeit", "erreich_x_R"] +RICHTUNGEN = ("MehrJam", "MehrFold", "Sonstige", "Unveraendert") + + +def mischung_text(mischung): + return ", ".join("%s %.0f%%" % (a, 100 * p) for a, p in mischung.items() if p > 0.0005) + + +def entscheidungszeilen(roh, beschreibung): + """Per changed decision one dict; `beschreibung`: {line index: {pos, linie, spieler, sonder}}.""" + out = [] + for r in roh: + b = beschreibung[r["i"]] + namen = r["namen"] + pi_alt, pi_neu = dict(zip(namen, r["pi_alt"])), dict(zip(namen, r["pi_neu"])) + rollen = dict(zip(namen, r["rollen"])) + richt, sh = W.richtung_zeile(rollen, pi_alt, pi_neu) + cov = {a: {c: r["cov"][i][j] for j, c in enumerate(namen)} for i, a in enumerate(namen)} + out.append({"linie": b["linie"], "pos": b["pos"], "spieler": b["spieler"], "sonder": b["sonder"], "key": r["key"], "klasse": r["klasse"], + "klasse_name": r["klasse_name"], "erreich": r["erreich"], "pi_alt": pi_alt, "pi_neu": pi_neu, "V": dict(zip(namen, r["V"])), "cov": cov, + "R": r["R"], "R_se": r["R_se"], "R_lo": W.untere_grenze(r["R"], r["R_se"]), "w": r["w"], "gespielt": r["gespielt"], + "richtung": richt, "shifts": sh, "erreich_x_R": r["erreich"] * r["R"]}) + return out + + +def wertzeilen(zeilen): + """Unique cells (node, class, line, position) with frequency n and value without dice; the same cell shares one estimate.""" + zellen = collections.OrderedDict() + for z in zeilen: + k = (z["key"], z["klasse"], z["linie"], z["pos"]) + zellen.setdefault(k, dict(z, n=0))["n"] += 1 + out = [] + for z in zellen.values(): + r = W.zeile(dict(z, se_V=None)) + if r: + r["lp"] = "%s|%s" % (z["linie"], z["pos"]) + out.append(r) + return W.sortiert(out) + + +def tsv(zeilen): + """TSV text, sorted by reach x R (descending), one line per changed decision.""" + kopf = "\t".join(SPALTEN) + zs = sorted(zeilen, key=lambda z: (-z["erreich_x_R"], z["key"], z["klasse"])) + t = [kopf] + for z in zs: + t.append("\t".join([z["linie"], z["pos"], str(z["spieler"]), ",".join(z["sonder"]) or "-", z["key"], z["klasse_name"], z["gespielt"] or "-", + mischung_text(z["pi_alt"]), mischung_text(z["pi_neu"]), z["richtung"], "%.3f" % z["R"], "%.3f" % z["R_se"], "%.3f" % z["R_lo"], + "%.2f" % z["w"], "%.5f" % z["erreich"], "%.5f" % z["erreich_x_R"]])) + return "\n".join(t) + "\n" + + +def zaehlen_je(zeilen, schluessel): + c = collections.Counter(schluessel(z) for z in zeilen) + return c + + +def markdown(zeilen, zaehlung, kopf, top=20, gezaehlt=None): + """AENDERUNGEN.md: counts per direction, line and position with value and interval; the `top` largest single changes (reach x R).""" + haende, entsch = zaehlung["haende"], zaehlung["entscheidungen"] + cells = wertzeilen(zeilen) + s = W.summen(cells, entsch, haende) + t = ["# Vorflop-selbst: Aenderungen an den Preflop-Entscheidungen des Archivs", "", kopf, ""] + if gezaehlt: + t += ["Archiv-Durchlauf des Dienstes: " + ", ".join("%s: %d" % (k, v) for k, v in gezaehlt.items()), ""] + t += ["Entscheidungen im Archiv: %d, davon geaendert: %d (%.1f %%), verschiedene (Knoten, Klasse, Lage): %d. Wert ohne Wuerfel (Summe (pi' - pi) V mit V der Suchfortsetzung): " + "%+.2f bb/100 Haende [%+.2f; %+.2f] (95 %%)." % (entsch, len(zeilen), 100.0 * len(zeilen) / max(entsch, 1), len(cells), s["wert_bb_pro_100"], s["lo_bb_pro_100"], s["hi_bb_pro_100"]), ""] + # direction + t += ["## Richtung", "", "| Richtung | Entscheidungen | verschiedene | Wert bb/100 [95 %] |", "|---|---|---|---|"] + for r in RICHTUNGEN: + zz = [z for z in zeilen if z["richtung"] == r] + cc = [c for c in cells if c["richtung"] == r] + v = W.summen(cc, len(zz), haende) if cc else None + t.append("| %s | %d | %d | %s |" % (r, len(zz), len(cc), "%+.2f [%+.2f; %+.2f]" % (v["wert_bb_pro_100"], v["lo_bb_pro_100"], v["hi_bb_pro_100"]) if v else "-")) + t += ["", "Richtung = die Rolle (Fold, Jam, Call/Raise) mit der groessten positiven Netto-Verschiebung der Entscheidung.", ""] + for titel, schl, denom in (("Je Linie", "linie", zaehlung["je_linie"]), ("Je Linie und Position", "lp", zaehlung["je_linie_position"])): + je = W.summen_je(cells, schl, denom, haende) + t += ["## " + titel, "", "| %s | Entscheidungen | geaendert | Jam mehr | Fold mehr | sonstige | Wert bb/100 [95 %%] |" % ("Linie" if schl == "linie" else "Linie, Position"), "|---|---|---|---|---|---|---|"] + for g, v in je.items(): + zz = [z for z in zeilen if (z["linie"] if schl == "linie" else "%s|%s" % (z["linie"], z["pos"])) == g] + c = collections.Counter(z["richtung"] for z in zz) + t.append("| %s | %d | %d | %d | %d | %d | %+.2f [%+.2f; %+.2f] |" % (g, v["entscheidungen"], len(zz), c["MehrJam"], c["MehrFold"], c["Sonstige"] + c["Unveraendert"], v["wert_bb_pro_100"], v["lo_bb_pro_100"], v["hi_bb_pro_100"])) + t.append("") + t += ["## Die %d groessten Einzelaenderungen (Erreichbarkeit x R)" % top, ""] + for i, z in enumerate(sorted(zeilen, key=lambda z: (-z["erreich_x_R"], z["key"], z["klasse"]))[:top]): + t.append("%d. %s, %s, %d Spieler%s, Klasse %s, Knoten %s: Tafel %s -> neu %s; gespielt %s; R %.2f +- %.2f bb (untere 95-%%-Grenze %.2f), w %.2f, Erreichbarkeit %.4f; Richtung %s." % ( + i + 1, z["linie"], z["pos"], z["spieler"], (", " + "/".join(z["sonder"])) if z["sonder"] else "", z["klasse_name"], z["key"][:8], mischung_text(z["pi_alt"]), mischung_text(z["pi_neu"]), + z["gespielt"] or "-", z["R"], z["R_se"], z["R_lo"], z["w"], z["erreich"], z["richtung"])) + return "\n".join(t) + "\n" diff --git a/messung/innovation/vorflop_selbst/sidecar.py b/messung/innovation/vorflop_selbst/sidecar.py index 7dac802d..3149382a 100644 --- a/messung/innovation/vorflop_selbst/sidecar.py +++ b/messung/innovation/vorflop_selbst/sidecar.py @@ -1,43 +1,65 @@ -"""Reader for the MOTOR_VORFLOP_SELBST sidecar and for the reason mark - ISOLATED because the real format is still unknown. +"""Reader for the MOTOR_VORFLOP_SELBST sidecar (format VSELBS02, written by `vorflop-selbst-bauen`; description: docs/vorflop_selbst.md in claude/vorflop-selbst-2). -STUB FORMAT (replace `lade`/`parse_marke` once the other branch (claude/vorflop-selbst) documents the real one): - sidecar JSON: {"format": "stub-1", "eintraege": [{"key": str, "klasse": int, "pi": {a: p}, "pi_neu": {a: p}, - "R": float, "R_se": float, "w": float, "V": {a: bb}, "se_V": {a: bb}, "cov": {a: {b: c}} | null}]} - reason mark : "[Vorflop-selbst -> R w ]" inside the answer's `reason`. +Header: "VSELBS02" | tau_ref2 f32 | alpha f32 | draws u32 | delta f32 x4 | (u8 length + text) x3: mode, stand, spiel_id. +Node record: key u64 | k u16 | a u8 | flags u8 (bit 0: classes present), then k classes of a + 11 bytes each: + pi' u8 x a (sum 255; the table bytes when unchanged) | w u8 (w * 255) | R f32 | R_se f32 | n u16 (hands; 0 = class not evaluated). +Little-endian. The sidecar holds mixtures and diagnostics only, no action values V; V comes from the rollouts of `vorflop-selbst-archiv` (rows read by `archiv_zeilen`). """ import json -import re +import struct -MARKE = re.compile(r"\[Vorflop-selbst\s+(?P[^\]]*?)->(?P[^\]]*?)\s+R\s+(?P\S+)\s+w\s+(?P\S+?)\]") -KLASSE = re.compile(r"Klasse (\d+)") -ANTEIL = re.compile(r"([\w.\-]+)\s+(\d+(?:\.\d+)?)%") +MAGIE = b"VSELBS02" -def parse_marke(reason): - """Reason mark -> {alt, neu, R, w} (strings as logged) or None.""" - m = MARKE.search(reason or "") - return m.groupdict() if m else None +def lies_kopf(b): + """Header -> (dict, length). ValueError for files that are not VSELBS02.""" + if b[:8] != MAGIE: + raise ValueError("not a VSELBS02 sidecar (magic %r)" % (b[:8],)) + tau, alpha, zieh = struct.unpack_from(" len(daten): + raise ValueError("truncated record") + if flags & 1: + self.lage[key] = (p + 12, k, a) + p += n + def knoten(self): + return len(self.lage) -def parse_mischung(text): - """'fold 0%, call 5%, 0.75x 95%' -> {'fold': 0.0, 'call': 0.05, '0.75x': 0.95} (whole percent, only a fallback).""" - return {a: float(p) / 100.0 for a, p in ANTEIL.findall(text or "")} - - -def knoten_schluessel(q_beschreibung, antwort): - """Node key of a request. STUB: line type + position + players + class; the real key comes from the motor CLI.""" - k = parse_klasse(antwort.get("reason")) - return "%s|%s|%d|%s" % (q_beschreibung["linie"], q_beschreibung["pos"], q_beschreibung["spieler"], k), k + def klasse(self, key, kl): + """-> dict(bytes=[pi' bytes], w=float, R=float, R_se=float, n=int) or None (node/class not in the sidecar).""" + e = self.lage.get(key) + if e is None or kl >= e[1]: + return None + o, _, a = e + o += kl * (a + 11) + b = list(self.daten[o:o + a]) + w = self.daten[o + a] / 255.0 + r, se, n = struct.unpack_from(" sidecar= [env=K=V ...] (switch ON and OFF through the service, parses the mark) python3 .../vorflop_selbst.py aus [n=500] [saat=1] (switch OFF: bit-identical on real requests) - python3 .../vorflop_selbst.py bericht (AENDERUNGEN.md + aenderungen.jsonl from lauf.jsonl) + python3 .../vorflop_selbst.py auswerten [roh=] (aenderungen-archiv.tsv on the SSD + AENDERUNGEN.md from the rows of `vorflop-selbst-archiv`) + python3 .../vorflop_selbst.py sidecar [key= klasse=] (read VSELBS02: header, node count, one class) + +The computation (rollouts for V, the changed decisions, the "sonstige" analysis) runs in the motor tool `vorflop-selbst-archiv` on the farm, see docs/vorflop_selbst.md +in claude/vorflop-selbst-2; this script only reads its output. Source (read only): /ein.jsonl (one request per line), ref.jsonl (logged live answers, same line order). Every exe run goes through werkzeuge/motorplatz.py --plaetze 2, nice 10. Outputs carry no player or hand IDs. @@ -21,6 +24,7 @@ sys.path.insert(0, HIER) import linien as L # noqa: E402 import sidecar as S # noqa: E402 import wert as W # noqa: E402 +import auswertung as A # noqa: E402 WURZEL = "/Users/marcmintel/Projects/pokerfreak" ARCHIV = "/Volumes/Alpha SSD/pokerfreak-daten/pruefstand/basis-rein" @@ -88,38 +92,6 @@ def dienst(exe, qs, env_zusatz): return out -def lauf(exe, opt): - """Runs the preflop requests with the switch ON; keeps the lines whose answer carries the mark.""" - sc = S.lade(opt["sidecar"]) - extra = dict(x.split("=", 1) for x in opt.get("env", "").split(",") if x) - es = list(preflop_entscheidungen()) - qs = [q for _, q, _, _, _ in es] - an = dienst(exe, qs, dict(extra, **{SCHALTER: "1"})) - ohne = dienst(exe, qs, {SCHALTER: "0"}) - zeilen = {} - for (i, q, b, k, _), a, o in zip(es, an, ohne): - marke = S.parse_marke(a.get("reason")) - key, klasse = S.knoten_schluessel(b, a) - e = sc.get((key, klasse)) - z = zeilen.setdefault((key, klasse), dict(b, key=key, klasse=klasse, n=0, markiert=marke is not None, e=e)) - z["n"] += 1 - rows = [] - for z in zeilen.values(): - e = z.pop("e") - if e is None or not z["markiert"]: - continue - r = W.zeile({"pi_alt": e["pi"], "pi_neu": e["pi_neu"], "V": e["V"], "cov": e.get("cov"), "se_V": e.get("se_V"), - "n": z["n"], "key": z["key"], "klasse": z["klasse"], "linie": z["linie"], "pos": z["pos"], - "spieler": z["spieler"], "sonder": z["sonder"], "R": e["R"], "R_se": e["R_se"], "w": e["w"]}) - if r: - rows.append(r) - with open(GROSS + "/lauf.jsonl.tmp", "w") as f: - for r in W.sortiert(rows): - f.write(json.dumps(r) + "\n") - os.replace(GROSS + "/lauf.jsonl.tmp", GROSS + "/lauf.jsonl") - print("rows changed:", len(rows), "of", len(zeilen), "unique decisions") - - def aus(exe_a, exe_b, opt): """Switch OFF: both exes answer identically on preflop + other streets (turn/river included) of the archive.""" n, saat = int(opt.get("n", 500)), int(opt.get("saat", 1)) @@ -144,33 +116,28 @@ def aus(exe_a, exe_b, opt): print(json.dumps({k: erg[k] for k in ("n", "je_strasse_gleich_anders", "anders")})) -def erklaerung(z): - d = W.differenz(z["pi_alt"], z["pi_neu"]) - ab = max(d, key=lambda a: -d[a]) - auf = max(d, key=lambda a: d[a]) - return ("%s, %s, %d Spieler, Klasse %s: %.0f %% weniger %s, %.0f %% mehr %s (Tafel behaelt Gewicht w=%.2f, der Rest geht auf die selbstkonsistente Antwort); Wert %+.3f bb je Vorkommen " - "[%+.3f; %+.3f], kommt %dx im Archiv vor." % (z["linie"], z["pos"], z["spieler"], z["klasse"], -100 * d[ab], ab, 100 * d[auf], auf, - z["w"], z["wert"], z["wert_lo"], z["wert_hi"], z["n"])) - - -def bericht(): - z = json.load(open(HIER + "/zaehlung.json")) - rows = list(lies(GROSS + "/lauf.jsonl")) - s = W.summen(rows, z["entscheidungen"], z["haende"]) - je = W.summen_je(rows, "linie", z["je_linie"], z["haende"]) - with open(HIER + "/aenderungen.jsonl", "w") as f: - for r in rows: - f.write(json.dumps({k: r[k] for k in ("key", "linie", "pos", "spieler", "klasse", "n", "pi_alt", "pi_neu", "R", "R_se", "w", "wert", "wert_se", "wert_lo", "wert_hi")}) + "\n") - t = ["# Vorflop-selbst: Aenderungen an allen Preflop-Entscheidungen des Archivs", "", - "Entscheidungen: %d, davon geaendert (eindeutig): %d (%d Vorkommen). Wert ohne Wuerfel: %+.2f bb/100 [%+.2f; %+.2f]." % ( - s["entscheidungen"], s["geaendert_eindeutig"], s["geaendert_vorkommen"], s["wert_bb_pro_100"], s["lo_bb_pro_100"], s["hi_bb_pro_100"]), - "", "| Linie | Entscheidungen | geaendert | bb/100 [95 %] |", "|---|---|---|---|"] - for l, v in je.items(): - t.append("| %s | %d | %d | %+.2f [%+.2f; %+.2f] |" % (l, v["entscheidungen"], v["geaendert_eindeutig"], v["wert_bb_pro_100"], v["lo_bb_pro_100"], v["hi_bb_pro_100"])) - t += ["", "## Top %d nach |Wert|" % TOP, ""] + ["%d. %s" % (i + 1, erklaerung(r)) for i, r in enumerate(rows[:TOP])] +def auswerten(opt): + """Rows of `vorflop-selbst-archiv` + archive description -> TSV (SSD) and AENDERUNGEN.md (repo; sums only).""" + roh = S.archiv_zeilen(opt.get("roh", GROSS + "/archiv-roh.jsonl")) + zaehlung = json.load(open(HIER + "/zaehlung.json")) + beschreibung = {z["i"]: z for z in lies(GROSS + "/entscheidungen.jsonl")} + zeilen = A.entscheidungszeilen(roh, beschreibung) + tmp = GROSS + "/aenderungen-archiv.tsv.tmp" + with open(tmp, "w") as f: + f.write(A.tsv(zeilen)) + os.replace(tmp, GROSS + "/aenderungen-archiv.tsv") + kopf = "Sidecar: %s" % opt.get("kopf", "sechs100-v2-suche-jam.vselbst (VSELBS02, Modus suche+jam, Delta-Prior aus vergleich2)") + text = A.markdown(zeilen, zaehlung, kopf) with open(HIER + "/AENDERUNGEN.md", "w") as f: - f.write("\n".join(t) + "\n") - print("\n".join(t[:12])) + f.write(text) + print(text[:1500]) + + +def sidecar_zeigen(pfad, opt): + sc = S.lade(pfad) + print(json.dumps(sc.kopf), "nodes:", sc.knoten()) + if "key" in opt: + print(sc.klasse(int(opt["key"], 16), int(opt.get("klasse", 0)))) def main(argv): @@ -179,12 +146,12 @@ def main(argv): opt = dict(x.split("=", 1) for x in rest if "=" in x) if cmd == "zaehlen": zaehlen() - elif cmd == "lauf": - lauf(pos[0], opt) elif cmd == "aus": aus(pos[0], pos[1], opt) - elif cmd == "bericht": - bericht() + elif cmd == "auswerten": + auswerten(opt) + elif cmd == "sidecar": + sidecar_zeigen(pos[0], opt) else: raise SystemExit(__doc__) diff --git a/messung/innovation/vorflop_selbst/wert.py b/messung/innovation/vorflop_selbst/wert.py index a0991aaa..710018a5 100644 --- a/messung/innovation/vorflop_selbst/wert.py +++ b/messung/innovation/vorflop_selbst/wert.py @@ -84,3 +84,31 @@ def summen_je(zeilen, schluessel, entscheidungen_je, haende): for z in zeilen: gruppen.setdefault(z[schluessel], []).append(z) return {g: summen(gruppen.get(g, []), entscheidungen_je[g], haende) for g in sorted(entscheidungen_je)} + + +ROLLEN_RICHTUNG = {"Fold": "MehrFold", "Jam": "MehrJam", "Sonst": "Sonstige"} +Z_EINSEITIG95 = 1.645 + + +def richtung_zeile(rollen, pi_alt, pi_neu): + """(direction, net shift per role) of one decision: the role with the largest positive net shift gets the mass (as the motor's `richtung`). + Mass moving only between call and raises changes no role total and counts as 'Unveraendert' here too (the motor's convention).""" + sh = {"Fold": 0.0, "Jam": 0.0, "Sonst": 0.0} + for a, d in differenz(pi_alt, pi_neu).items(): + sh[rollen[a]] += d + if all(abs(x) < VERAENDERT_AB for x in sh.values()): + return "Unveraendert", sh + return ROLLEN_RICHTUNG[max(sh, key=lambda k: sh[k])], sh + + +def untere_grenze(r, se): + """Lower one-sided 95 % bound of a normally estimated quantity.""" + return r - Z_EINSEITIG95 * se + + +def klassenname(k): + """Preflop class 0..169 as in karten.rs: pairs on the diagonal, suited = high * 13 + low, offsuit = low * 13 + high.""" + r = "23456789TJQKA" + x, y = divmod(k, 13) + h, l = max(x, y), min(x, y) + return "%s%s%s" % (r[h], r[l], "" if x == y else ("s" if x > y else "o")) diff --git a/tests/innovation_vorflop_selbst_spec.py b/tests/innovation_vorflop_selbst_spec.py index ee270a16..9ea58d72 100644 --- a/tests/innovation_vorflop_selbst_spec.py +++ b/tests/innovation_vorflop_selbst_spec.py @@ -12,6 +12,9 @@ while _w != "/" and not os.path.isdir(os.path.join(_w, "messung")): sys.path.insert(0, os.path.join(_w, "messung", "innovation", "vorflop_selbst")) import linien as L # noqa: E402 import wert as W # noqa: E402 +import sidecar as S # noqa: E402 +import auswertung as A # noqa: E402 +import struct # noqa: E402 def h(seat, a, amt=None): @@ -138,5 +141,110 @@ class Wert(unittest.TestCase): W.summen([], 0, 0) +def _sidecar_bytes(): + kopf = b"VSELBS02" + struct.pack("