diff --git a/messung/motor/temperatur/flopmenue_pool.py b/messung/motor/temperatur/flopmenue_pool.py new file mode 100644 index 00000000..df20c332 --- /dev/null +++ b/messung/motor/temperatur/flopmenue_pool.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Value of OUR flop GG strategy against the NL2 pool, per flop, menu and side (flop library images, format flopbib-2). + +Pool model (first level): wherever the opponent faces OUR bet/raise he folds the fraction f(s) of his reach-weighted range with the +lowest Q(call)-Q(fold), the rest calls (no raises; the measured table has no raise split). Everywhere else both sides play GG. +Our value per hand x for move a is sum_b P(b|x) U(x,a,b) with U from the image (value of the other player after his move b); this ignores +that his range after b differs from GG's (stated approximation). Control: pool := his GG strategy reproduces header `werte_wurzel`. + + nice -n 10 python3 -I flopmenue_pool.py [--bilder DIR] [--aus FILE.jsonl] [--prozesse 3] +""" +import collections +import gzip +import json +import math +import multiprocessing +import os +import re +import subprocess +import sys + +import numpy as np + +sys.dont_write_bytecode = True + +DATEN = "/Volumes/Alpha SSD/pokerfreak-daten/temperatur/flopmenue" +TAFEL_REF = "claude/sim-gekauft-905238:messung/motor/antwort_eichung_gekauft/antwort-tafel-gekauft-fein-v1.txt" +LAGEN = DATEN + "/paket/x/lagen.jsonl" +ISO = DATEN + "/paket/x/iso-flops.txt" +LINIE = "BTN-BB" +BB_NL2 = 0.02 +STRASSE_FLOP = 1 +CHIPS_PRO_BB = 100.0 # chips in the images are 1/100 bb +HART = 0.1 # flop_ranges floor relative to the max weight (flopbib.rs) +RAENGE = "23456789TJQKA" +FARBEN = "cdhs" +BAND_OBEN = (0.45, 0.85, 1.3, 2.0, 3.5, 6.0, 99.0) + + +# ---------------------------------------------------------------- pool fold curve + +def lies_tafel(text, bb=BB_NL2, strasse=STRASSE_FLOP): + """Return ({band_upper: [folds, n]} non-all-in, {band_upper: [folds, n]} all-in, {band_upper: median}) summed over responder types.""" + ohne, mit = collections.defaultdict(lambda: [0, 0]), collections.defaultdict(lambda: [0, 0]) + med = collections.defaultdict(lambda: [0.0, 0]) + for z in text.splitlines(): + w = z.split("#")[0].split() + if not w or float(w[1]) != bb or int(w[3]) != strasse: + continue + if w[0] == "F": + ziel = mit if int(w[5]) else ohne + ziel[float(w[4])][0] += int(w[6]) + ziel[float(w[4])][1] += int(w[7]) + elif w[0] == "T": + n, m = int(w[5]), float(w[6]) + med[float(w[4])][0] += n * m + med[float(w[4])][1] += n + return dict(ohne), dict(mit), {b: s / n for b, (s, n) in med.items() if n} + + +def logistik_fit(punkte): + """Binomial maximum likelihood of fold = logistic(a + b ln s); punkte = [(s, folds, n)]. Newton/IRLS, returns (a, b).""" + x = np.log([p[0] for p in punkte]) + k = np.array([p[1] for p in punkte], float) + n = np.array([p[2] for p in punkte], float) + beta = np.array([0.0, 0.0]) + X = np.stack([np.ones_like(x), x], 1) + for _ in range(50): + p = 1 / (1 + np.exp(-X @ beta)) + grad = X.T @ (k - n * p) + hess = (X * (n * p * (1 - p))[:, None]).T @ X + schritt = np.linalg.solve(hess, grad) + beta = beta + schritt + if np.max(np.abs(schritt)) < 1e-10: + break + return float(beta[0]), float(beta[1]) + + +class Pool: + """Fold rate vs bet size (bet or call amount over pot before the action).""" + + def __init__(self, ohne, mit, med): + self.ohne, self.mit, self.med = ohne, mit, med + self.a, self.b = logistik_fit([(med.get(bis, bis), ohne[bis][0], ohne[bis][1]) for bis in sorted(ohne)]) + + def fold(self, s, allin=False): + if allin: + bis = next((b for b in sorted(self.mit) if s <= b), max(self.mit)) + return self.mit[bis][0] / self.mit[bis][1] + return 1 / (1 + math.exp(-(self.a + self.b * math.log(s)))) + + +def pool_aus_git(): + wurzel = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + text = subprocess.run(["git", "-C", wurzel, "show", TAFEL_REF], capture_output=True, text=True, check=True).stdout + return Pool(*lies_tafel(text)) + + +# ---------------------------------------------------------------- image + +def f16(buf, off, n): + return np.frombuffer(buf, dtype=" b else (b, a) + return a * (a - 1) // 2 + b + + +def hand_karten(h): + return karte(h[0:2]), karte(h[2:4]) + + +def flop_ranges(roh, flop): + """Port of flopbib::flop_ranges for one side: board cards out, normalise to max, below HART to 0.""" + w = np.array(roh, float) + for a in range(52): + for b in range(a): + if a in flop or b in flop: + w[paar(a, b)] = 0.0 + w = w / max(w.max(), 1e-30) + w[w < HART] = 0.0 + return w + + +def lagen_ranges(): + with open(LAGEN) as f: + for z in f: + v = json.loads(z) + if v["linie"] == LINIE: + return v["ranges"] + raise ValueError(LINIE) + + +class Bild: + """Decoded flopbib-2 image: nodes by path with strategy, Q of the mover, value of the other player after each move.""" + + def __init__(self, roh_bytes, ranges_roh): + kopf_text, daten = roh_bytes.split(b"\n", 1) + self.kopf = k = json.loads(kopf_text) + flop = [karte(k["flop"][i:i + 2]) for i in (0, 2, 4)] + self.haende = [[hand_karten(h) for h in k["haende"][p]] for p in (0, 1)] + self.gew = [] + for p in (0, 1): + w = flop_ranges(ranges_roh[p], flop) + idx = [paar(*c) for c in self.haende[p]] + gesetzt = set(np.nonzero(w)[0].tolist()) + if set(idx) != gesetzt: + raise ValueError(f"hands of player {p} differ from the lagen range ({len(idx)} vs {len(gesetzt)})") + self.gew.append(w[idx]) + n = [len(h) for h in self.haende] + self.vertraeglich = np.array([[0.0 if set(x) & set(y) else 1.0 for y in self.haende[1]] for x in self.haende[0]]) + self.knoten = {} + off = 0 + for kn in k["knoten"]: + m, p = len(kn["zuege"]), kn["spieler"] + self.knoten[tuple(kn["weg"])] = dict(spieler=p, zuege=kn["zuege"]) + self.knoten[tuple(kn["weg"])]["s"] = np.frombuffer(daten, dtype=" 0, np.clip((ziel - (cm - ms)) / np.where(ms > 0, ms, 1.0), 0.0, 1.0), 0.0) + pf = np.zeros_like(m) + pf[:, ordnung] = anteil + return m, pf + + def wert(weg, rv): + kn = bild.knoten[weg] + zuege, n_u = kn["zuege"], len(bild.haende[u]) + if kn["spieler"] == u: + V = np.zeros(n_u) + for a in range(len(zuege)): + kind = weg + (a,) + # part 1 (Q) is net of the chips this move adds; part 2 and the recursion value of his node are not (measured: Q = sum_b P U_b - added chips) + W = wert(kind, rv) - (bild.strasse_einsatz(kind)[u] - bild.strasse_einsatz(weg)[u]) / CHIPS_PRO_BB if kind in bild.knoten else kn["q"][a] + if spur is not None and kind in bild.knoten: + gw = bild.gew[u] * (C @ rv) + spur.append((weg, a, float((gw * (kn["q"][a] - W)).sum() / gw.sum()))) + V += kn["s"][a] * W + return V + aggr = bild.aggressiv(weg) if pool is not None else None + if aggr is not None and aggr[0] == u: + m, pf = antworte_pool(weg, kn, rv, aggr[1], aggr[2]) + gesamt = m.sum(axis=1) + pb = {kn["zuege"].index("Fold"): pf, kn["zuege"].index("Call"): 1.0 - pf} + V = np.zeros(n_u) + for b, p in pb.items(): + Pb = np.where(gesamt > 0, (m * p).sum(axis=1) / np.where(gesamt > 0, gesamt, 1.0), 0.0) + V += Pb * kn["u"][b] + return V + m = C * rv[None, :] + gesamt = m.sum(axis=1) + V = np.zeros(n_u) + for b in range(len(zuege)): + rb = rv * kn["s"][b] + Pb = np.where(gesamt > 0, (C * rb[None, :]).sum(axis=1) / np.where(gesamt > 0, gesamt, 1.0), 0.0) + kind = weg + (b,) + V += Pb * (wert(kind, rb) if kind in bild.knoten else kn["u"][b]) + return V + + V = wert((), bild.gew[v]) + w = bild.gew[u] * (C @ bild.gew[v]) # solver's normalized weights: own weight times the opponent mass that x does not block + return float((w * V).sum() / w.sum()) + + +def groessen_anteile(bild): + """Our bet share by size at the first aggressive decision: OOP at the root, IP after a check (range-weighted).""" + aus = {} + for seite, weg in ((0, ()), (1, (0,))): + kn = bild.knoten[weg] + w = bild.gew[seite] + for a, name in enumerate(kn["zuege"]): + m = re.match(r"(Bet|Raise|AllIn)\((\d+)\)", name) + marke = "check" if name == "Check" else f"{round(100 * int(m.group(2)) / bild.pot)}%" if m else name + aus[f"{'oop' if seite == 0 else 'ip'}:{marke}"] = float((w * kn["s"][a]).sum() / w.sum()) + return aus + + +def datei_aufgabe(args): + pfad, flop, menue, z, ranges_roh, pool = args + try: + bild = Bild(gzip.open(pfad).read(), ranges_roh) + except Exception as e: # one broken image must not stop the run + return [dict(flop=flop, menue=menue, z=z, fehler=str(e))] + wurzel = bild.kopf["werte_wurzel"] + zeilen = [] + for u in (0, 1): + kontrolle = bewerte(bild, u, None) + zeilen.append(dict(flop=flop, menue=menue, z=z, seite="oop" if u == 0 else "ip", wert_pool_bb=bewerte(bild, u, pool), + wert_gg_kontrolle_bb=kontrolle, werte_wurzel_kopf_bb=wurzel[u], kontrolle_abw_bb=abs(kontrolle - wurzel[u]), + luecke_topf=bild.kopf["luecke_topf"], fertig=bild.kopf["fertig"], groessen=groessen_anteile(bild))) + return zeilen + + +def aufgaben(bilder, pool, ranges_roh): + for ordner in sorted(os.listdir(os.path.join(bilder, LINIE))): + m = re.match(r"(.+)-z([0-9.]+)$", ordner) + if not m: + continue + for f in sorted(os.listdir(os.path.join(bilder, LINIE, ordner))): + if f.endswith(".bin.gz"): + yield (os.path.join(bilder, LINIE, ordner, f), f[:-7], m.group(1), m.group(2), ranges_roh, pool) + + +BOOTSTRAP_N = 4000 +BOOTSTRAP_SEED = 20261204 + + +def iso_gewichte(): + with open(ISO) as f: + return {z.split()[0]: int(z.split()[1]) for z in f if z.strip()} + + +def auswerten(pfad, paar=("eng", "breit")): + """Mean difference menu B minus menu A of the pool value per side and z over flops present in both, with a flop-cluster bootstrap 95 % interval. + + Reported twice: weighted by the iso-flop class size (prevalence of real flops) and unweighted.""" + with open(pfad) as f: + zeilen = [json.loads(z) for z in f] + zeilen = [z for z in zeilen if "fehler" not in z] + wert = {(z["flop"], z["menue"], z["z"], z["seite"]): z["wert_pool_bb"] for z in zeilen} + gewicht = iso_gewichte() + rng = np.random.default_rng(BOOTSTRAP_SEED) + aus = [] + for z in sorted({z["z"] for z in zeilen}): + for seite in ("oop", "ip"): + flops = sorted(f for (f, m, zz, s) in wert if m == paar[0] and zz == z and s == seite and (f, paar[1], z, seite) in wert) + if not flops: + continue + d = np.array([wert[(f, paar[1], z, seite)] - wert[(f, paar[0], z, seite)] for f in flops]) + w = np.array([gewicht[f] for f in flops], float) + for name, gew in (("gewichtet", w), ("ungewichtet", np.ones_like(w))): + mittel = float((d * gew).sum() / gew.sum()) + idx = rng.integers(0, len(d), (BOOTSTRAP_N, len(d))) + bs = (d[idx] * gew[idx]).sum(1) / gew[idx].sum(1) + aus.append(dict(z=z, seite=seite, gewicht=name, flops=len(flops), mittel_bb=mittel, + ci95=[float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))], differenz=f"{paar[1]} - {paar[0]}")) + return aus + + +def main(argv): + bilder, aus, prozesse = DATEN + "/bilder", DATEN + "/wert-gegen-pool.jsonl", 3 + it = iter(argv) + for a in it: + if a == "--bilder": + bilder = next(it) + elif a == "--aus": + aus = next(it) + elif a == "--auswerten": + for z in auswerten(next(it)): + print(json.dumps(z)) + return + elif a == "--prozesse": + prozesse = min(4, int(next(it))) + pool = pool_aus_git() + print(f"fold curve: logistic({pool.a:.4f} + {pool.b:.4f} ln s); all-in rows {pool.mit}", file=sys.stderr) + ranges_roh = lagen_ranges() + todo = list(aufgaben(bilder, pool, ranges_roh)) + with multiprocessing.Pool(prozesse) as p, open(aus + ".tmp", "w") as f: + for zeilen in p.imap_unordered(datei_aufgabe, todo, chunksize=2): + for z in zeilen: + f.write(json.dumps(z) + "\n") + os.replace(aus + ".tmp", aus) + print(f"{len(todo)} images -> {aus}", file=sys.stderr) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/tests/flopmenue_pool_spec.py b/tests/flopmenue_pool_spec.py new file mode 100644 index 00000000..4510870e --- /dev/null +++ b/tests/flopmenue_pool_spec.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Spec of messung/motor/temperatur/flopmenue_pool.py: the fold-curve fit and the GG control (pool := GG reproduces the image header). + + python3 tests/flopmenue_pool_spec.py -v +The control needs one image under the flopmenue data folder and is skipped if none is there yet.""" +import glob +import gzip +import math +import os +import sys +import unittest + +_w = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(os.path.join(os.path.dirname(_w), "messung", "motor", "temperatur")) +import flopmenue_pool as F + +KONTROLLE_TOL_BB = 2e-3 # f16 noise of the stored values + + +class Fit(unittest.TestCase): + def test_logistik_fit_findet_bekannte_kurve(self): + a, b = -0.3, 1.1 + n = 1_000_000 + punkte = [(s, round(n / (1 + math.exp(-(a + b * math.log(s))))), n) for s in (0.33, 0.55, 1.0, 1.6, 2.6, 4.5, 11.0)] + fa, fb = F.logistik_fit(punkte) + self.assertAlmostEqual(fa, a, places=3) + self.assertAlmostEqual(fb, b, places=3) + + def test_pool_steigt_mit_der_groesse_und_allin_nimmt_die_allin_zeile(self): + ohne = {0.45: [33, 100], 0.85: [47, 100], 1.3: [60, 100]} + mit = {0.45: [1, 10], 99.0: [8, 10]} + p = F.Pool(ohne, mit, {0.45: 0.333, 0.85: 0.545, 1.3: 1.0}) + self.assertLess(p.fold(0.33), p.fold(0.75)) + self.assertLess(p.fold(0.75), p.fold(1.25)) + self.assertEqual(p.fold(12.0, allin=True), 0.8) + + +class Kontrolle(unittest.TestCase): + def test_pool_gleich_gg_ergibt_den_wurzelwert_des_kopfes(self): + dateien = sorted(glob.glob(F.DATEN + "/bilder/BTN-BB/*/*.bin.gz"))[:6] + if not dateien: + self.skipTest("no images yet") + ranges = F.lagen_ranges() + for d in dateien: + bild = F.Bild(gzip.open(d).read(), ranges) + for u in (0, 1): + self.assertAlmostEqual(F.bewerte(bild, u, None), bild.kopf["werte_wurzel"][u], delta=KONTROLLE_TOL_BB, msg=d) + + +if __name__ == "__main__": + unittest.main()