From 09e38ac196826280725745291b58dd673f2920c0 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sun, 6 Dec 2026 00:04:57 +0100 Subject: [PATCH 1/2] Pool opponent table export (Welt v5.1): core, reader, writer, spec, held-out evaluation tools Table of P(6 classes) per node x q bin / start-hand class with n, kappa, fallback flags, marginal recalibration (p_kal), gegen-uns variant and live cross-check columns. Co-Authored-By: Claude Sonnet 5.5 --- messung/motor/poolgegner_tafel/FORMAT.md | 71 ++++ messung/motor/poolgegner_tafel/KARTE.md | 28 ++ messung/motor/poolgegner_tafel/aggregat.py | 102 ++++++ messung/motor/poolgegner_tafel/auswerten.py | 171 +++++++++ messung/motor/poolgegner_tafel/bauen.py | 169 +++++++++ messung/motor/poolgegner_tafel/bewerten.py | 191 ++++++++++ messung/motor/poolgegner_tafel/flop_rang.py | 69 ++++ messung/motor/poolgegner_tafel/kern.py | 340 ++++++++++++++++++ messung/motor/poolgegner_tafel/lesen.py | 83 +++++ messung/motor/poolgegner_tafel/modellwahl.py | 88 +++++ messung/motor/poolgegner_tafel/schreiben.py | 90 +++++ messung/motor/poolgegner_tafel/vektoren.py | 86 +++++ .../poolgegner_tafel/vergleich_temperatur.py | 173 +++++++++ tests/poolgegner_tafel_spec.py | 334 +++++++++++++++++ 14 files changed, 1995 insertions(+) create mode 100644 messung/motor/poolgegner_tafel/FORMAT.md create mode 100644 messung/motor/poolgegner_tafel/KARTE.md create mode 100644 messung/motor/poolgegner_tafel/aggregat.py create mode 100644 messung/motor/poolgegner_tafel/auswerten.py create mode 100644 messung/motor/poolgegner_tafel/bauen.py create mode 100644 messung/motor/poolgegner_tafel/bewerten.py create mode 100644 messung/motor/poolgegner_tafel/flop_rang.py create mode 100644 messung/motor/poolgegner_tafel/kern.py create mode 100644 messung/motor/poolgegner_tafel/lesen.py create mode 100644 messung/motor/poolgegner_tafel/modellwahl.py create mode 100644 messung/motor/poolgegner_tafel/schreiben.py create mode 100644 messung/motor/poolgegner_tafel/vektoren.py create mode 100644 messung/motor/poolgegner_tafel/vergleich_temperatur.py create mode 100644 tests/poolgegner_tafel_spec.py diff --git a/messung/motor/poolgegner_tafel/FORMAT.md b/messung/motor/poolgegner_tafel/FORMAT.md new file mode 100644 index 00000000..994b707e --- /dev/null +++ b/messung/motor/poolgegner_tafel/FORMAT.md @@ -0,0 +1,71 @@ +# poolgegner-tafel v1 (format, 05.12.2026) -- agreed with the trainer side (answers relayed from "Nachtlerner" via main) + +Purpose: the calibrated NL2 pool opponent (Welt v5.1-r4 + "gegen uns" delta) as a lookup table for a trainer that uses it as a fixed opponent (restricted Nash response). +Source of truth: `messung/batterie/v2/welt_v5` (messlatte.V5Modell). The table is a DERIVED view; `tests/poolgegner_tafel_spec.py` checks it against the model. +No hand ids, player ids or hands are in the files, only sums / probabilities / parameters. Transitional supplier (see "Replacement conditions"). + +## Agreed points (trainer side: Rust external-sampling MCCFR, fixed-opponent template `Target::probs`) +1. Pool only (no per-type tables); types later as a mixture with per-player posterior weights, not 48 hard types. +2. Legal mask: `p * mask`, renormalised. If the mask leaves no mass (mask outside the cell's typical mask) the reader uses uniform over the legal classes and counts the case + (`Tafel.zaehler["maske_ausserhalb"]`; per street in `meta.maske_ausserhalb` from the held-out run). The `u + o_ref` route is NOT shipped (not needed once the count is small); `o_ref`, `mask_ref`, `p_ref` are there for audits. +3. `p_gegenuns` for decisions that face a bet of the trained player. Cells with `bekanntes_fehl = 1` (river, bet faced < 0.45 pot: small leads <= 25 % pot and 25-50 % out of position, STUFE1.md): the trainer sets p = 0 there (equilibrium instead of a known-wrong model). +4. Primary format = flat little-endian binary + JSON header (mmap, no numpy): `.bin` + `.kopf.json` (name, dtype, shape, byte offset per array). `.npz` has the same arrays for Python. + Delivered: test vectors (200-500, all streets), exact strength definition + strength tables per test board, node-code spec cases (public history -> fine code) -- `testvektoren.*`. + +## 0. Files (folder `pruefstand/poolgegner-tafel//`, never overwritten, `SHA256SUMS`) +`meta.json` (sources + SHAs, axes, class names, kappa tables, size distributions, live cross-check tables, held-out results, replacement conditions), `nachflop.{bin,kopf.json,npz}`, `vorflop.{bin,kopf.json,npz}`, +`lesen.py` (reference reader, pure numpy), this file. Test vectors in `testvektoren/` next to the build. + +## 1. Axes +- axis 0 = `limit` (feature column, length L = 1): `meta.limit.bb = [0.02]`, only NL2 is filled. Other limits: a further slice with `n = 0` (no data, p = model extrapolation via lambda[a]*log2(bb/0.02), all zeros today, not an NL2 fallback -- the consumer must treat n = 0 as "no knowledge"). +- types: pool = mixture of the 48 types + pseudo type -1 (unknown player, alpha = pool-coarse only), weighted by the posterior mass of each type at the node. +- action classes a = 0..5: 0 fold, 1 check/call, 2..5 bet/raise classes (post-flop 2..5 = size bands of the increase over the call / pot-after-call: [0,0.45) [0.45,0.85) [0.85,1.2) [1.2,inf); preflop 2,3,4 = raise fach 0..2 by multiples of the open, 5 = all-in). +- node code = `welt_v4/knoten.py` fine code. Preflop 900 valid codes (of 2048), post-flop 1944 (2048 + street*648 + ...; flop, turn, river). ALL valid codes are in the table; reachable or not (see `aufgefuellt`). + medium / coarse levels (`hoch(c, 1)`, `hoch(c, 2)`) are in arrays prefixed `l1_`, `l2_` (post-flop): `code`, `p`, `n`, `na`, `p_emp`, `aufgefuellt` (p = mass-weighted mean of the children). +- q bin: 20 equal bins of [0,1], bin(q) = min(int(q*20), 19); post-flop P is evaluated at the bin centre. Preflop: no q axis, the 169 start-hand classes (`meta.klassen`, `gamma.KLASSEN` order); q of the class is baked in at the data-weighted mean q of (node, class) (`qbar`), static q of the class without data. + +## 2. Arrays (shape [L, N, B or 169, 6] unless noted; float32; N = nodes; post-flop B = 20) +| array | meaning | +|---|---| +| `code` [N] int32 | fine node code | +| `p` | P(a) = mixture over the variants (type, legal mask, o) seen at the node (top 16 by mass). **Model as exported.** Rows sum to 1, 0 on classes never legal at the node | +| `p_kal` | `p` with ONE logit shift per node and action (`kal_delta` [L,N,6]) so that the data-weighted node marginal equals the observed node frequency (shrunk to the model with the EB kappa of `meta.kappa.marginal`). Hand ordering inside the node is the model's. **Recommended default if the held-out table says so (meta.heldout)** | +| `p_schrumpf` | (n p_emp + kappa p)/(n + kappa), cell level; equals p where n = 0 or kappa = inf | +| `p_gegenuns` | `p` with the live-calibrated delta for decisions facing a bet of the trained player (`gegen_gilt` [L,N] tells where it applies, else = p); node-averaged band (post-flop gegen 1 = mean of bands 0 and 1); exact re-evaluation: `meta.gegenuns.delta` + rule in `gegenuns.zelle` | +| `p_ref`, `o_ref` [L,N,6], `mask_ref` [L,N] uint8 | exact model under the single most frequent variant (audit) | +| `n` [L,N,B], `na` [..,6], `p_emp` | posterior-weighted counts (E-step weights) of the cell, split by observed action; `p_emp` NaN where n = 0. n are weights over hidden cards, not integer observations: effective sample size is smaller | +| `n_knoten` [L,N] | sum of n | +| `kappa` [L,N] | empirical-Bayes kappa of the (street, fallback level) group of cell deviations around the model (Beta-binomial moments, `antworttafel_v3.kappa`); inf = no over-dispersion | +| `stufe` [L,N] uint8 | alpha fallback level used by the type mass majority: 0 fine, 1 medium, 2 coarse, 3 pool-coarse, 4 none (alpha = 0); ties go to the coarser level | +| `anteil_fein` [L,N] | share of type mass with a FINE alpha | +| `aufgefuellt` [L,N] | 1 = no type has a fine alpha: the cell comes from fallback only | +| `aufgefuellt_leer` [L,N] | 1 = last resort, stufe 4 (alpha = 0): P = softmax(beta.B(q) + o) over the legal classes (uniform-over-legal where beta = 0) | +| `bekanntes_fehl` [L,N] | 1 = known misfit, consumer reads p = 0 (equilibrium) there | +| `gegen_live_k/n/lo/hi`, `gegen_modell_fold`, `gegen_modell_fold_gegenuns` [L,N] | live cross-check of "response to our bets": live fold k of n, Wilson 95 %, model fold (q-marginal) without / with the delta; filled for post-flop nodes facing a bet 1..4, turn/river | +| `qbar` (preflop) [L,N,169] | q baked in | +Per node-class tables in `meta`: `gegenuns_live` (street, bet band, our position), `stufe1_live` (STUFE1 cells with Wilson intervals and the models), `kappa`, `heldout`, `modellwahl`. + +## 3. Query: how the opponent's q is computed (forward range) +The opponent plays a FIXED strategy, so its range at a decision follows from its own earlier actions in this hand; it does not know our cards: +1. w0(h) = 1 for each of the 1326 combos without a card of the CURRENT board (also for earlier streets: Welt5 does it this way; hero and other seats' cards are NOT removed). Ref: `welt_v5.py Welt5.reichweite`. +2. Per earlier decision d' of this seat (street st', fine code c', observed class a'): w(h) <- w(h) * P(a' | d', h) with P = the table row used at that decision (variant `p`, renormalised over the legal mask). eps = 0. If the mass would become 0 keep the old w. +3. Strength order s(h) at the current decision: preflop `meta.vorflop_staerke` (169 values, class of h); flop `staerke_v5.brett_staerke_v5` = mean over the 49 deterministic runouts j = 0, 24, 48, ... of the lexicographically ordered (turn < river) pairs of the 49 free cards; turn mean over the 46 rivers; river exact (`staerke.werte`, percentile among live combos). NaN for combos on the board. Only the ORDER (with ties |ds| <= 1e-12) matters. Per-board tables for the test boards: `testvektoren.npz: s`. +4. q(h) = (mass of combos with s < s(h) - 1e-12 + half the mass of combos with |s - s(h)| <= 1e-12) / total mass, mass = w (midpoint rule); NaN strength has mass 0; total mass 0 -> q = 0.5. `lesen.quantil`. +5. bin = min(int(q*20), 19); P(. | d, h) = `p[node, bin]` (post-flop) or `p[node, class(h)]` (preflop: no q), times legal mask, renormalised. +Because external sampling draws all hole cards, the trainer knows h and draws from P(. | d, h); w depends only on the public history + board and is cached per (history, board). +Node code at query time from the public history exactly as `knoten.Lauf.knoten(i)`; spec cases in `testvektoren.json` (history -> `code`). +**Flop axis check** (49 vs all 1176 runouts): `meta.flop_rang` (Spearman per board, effect on q). +Absolute strength (shared opponent model v3): the relative q axis is primary; an absolute `pz` axis is not in v1 of this table (comparison "one axis alone worse?" not run, see KARTE). + +## 4. Sizes (bet/raise classes 2..5) +`meta.groessen`: post-flop `p[street][art bet|raise][class j][24 log steps of bet/pot-after-call from 0.05 to 10]` plus all-in share `allin[street][art][j][stack band]`; +preflop `p[lage][20 log steps of the raise-to as multiple of the current high bet from 1.5 to 30]`, `allin[lage][fach][stack band]`. Rule (`Welt.groesse`): all-in share first, then a step by weight clipped to the legal [min, max], uniform in log inside the step. Not conditional on q. + +## 5. Known misfit and cross-check against live (not painted over) +"Response to our bets": columns above and `meta.gegenuns_live` / `meta.stufe1_live`; river bets < 0.45 pot are flagged (`bekanntes_fehl`). Which model is better where (v5.1 against the measured response curve of "Gegner-Temperatur", same rows, same held-out days 308-385): `meta.modellwahl`. + +## 6. Replacement conditions (v5.1 is a transitional supplier) +- v5.1 table: replaced when the shared opponent model v3 (docs/notizen/GEGNERMODELL.md) ships the same cells with an identified supplier per node class and a check card per class that beats it on held-out days. +- response curve (Temperatur): replaced per node class when v5.1 or its successor beats it on the same rows with an interval above 0 (see `modellwahl`). +- jam-band tables: replaced when the all-in cells (class 5) of the shared model are identified with their own check card. +Anything chosen by hand in `modellwahl` is labelled "ungeprueft". diff --git a/messung/motor/poolgegner_tafel/KARTE.md b/messung/motor/poolgegner_tafel/KARTE.md new file mode 100644 index 00000000..81d716c2 --- /dev/null +++ b/messung/motor/poolgegner_tafel/KARTE.md @@ -0,0 +1,28 @@ +--- +titel: Poolgegner-Tafel (Welt v5.1 als Tabelle fuer den Trainer) +strang: motor +plan: Pilot SHARINGAN gegen kalibrierten NL2-Pool (Schritt 0 Export, Stufe 1 Tragfaehigkeit) +frage: Traegt die exportierte Tafel (Knoten x q-Bin, Pool ohne Typ, Maske renormiert) als fester Trainingsgegner, je Strasse, auf zurueckgehaltenen gekauften Haenden? +tor: Je Strasse: Log-Loss je Entscheidung besser als (a) Knoten-Haeufigkeit ohne Handstaerke UND (b) Gleichverteilung ueber Legale (95-%-Bootstrap ueber Spieler, Intervall der Differenz ueber 0); PIT der wahren Hand nicht schief (mittleres PIT 0,5 +-0,03); Zellen mit n < 50 bei hoechstens 10 % der Entscheidungsmasse. Vorflop oder Flop verfehlt = Pilot endet dort. Vor dem Lauf festgelegt (05.12.). +decke: Vorflop (Messlatte v5.1 gegen Haeufigkeit +0,056 nats/Entscheidung, Stand MESSLATTE.md); River laut Stufe 1 praktisch 0 (v5 - Haeufigkeit -0,002 [-0,008; +0,002]). Aufloesung bei 410.000 Entscheidungen: Halbbreite < 0,01 nats je Strasse. +abbruch: kein Zwischenlauf (ein Durchgang ueber die 50.000 Haende, Minuten). +quelle: hhDealer NL2 (gekaufte Haende, Welt-v5-Pruefmenge ab 22.07.2026, 113 Tage; Lernen Tage davor) +status: laeuft +ergebnis: – +entscheidung: offen +punkt: – +erwartet: Vorflop +0,03 bis +0,05 nats/Entscheidung gegen Haeufigkeit; Flop +0,01 bis +0,02; Turn +0,005; River 0 (+-0,01); River-Antwort auf kleine Einsaetze (<= 25 % Topf) deutlich ausserhalb der Live-Fold-Rate (Modell 36-43 % gegen live 13 %) +richter: geprueft: zurueckgehaltene gekaufte Haende (gleiche Tage und Haende wie die Messlatte); Live-Gegenprobe nur fuer 'Antwort auf unsere Einsaetze' +schalter: – +buendel: – +stand: 2026-12-05 +bericht: BERICHT.md +starter: – +nachfolger: – +eichung: – +stackoff: – +--- + +Export: `python3 bauen.py --aus ` (Ordner unter `/Volumes/Alpha SSD/pokerfreak-daten/pruefstand/poolgegner-tafel/`, SHA256SUMS, nie ueberschreiben). Format: `FORMAT.md` im Ordner. +Pruefung: `python3 tests/poolgegner_tafel_spec.py` (Wahrscheinlichkeiten, Modell = Tafel, Rueckfall-Flags, kappa, Leser). Held-out: `bewerten.py`, `auswerten.py`; Ergebnisse unter `.../poolgegner-tafel/heldout/`. +Daten mit Handbezug liegen nur auf der SSD (E-Schritt-Ausgaben `welt_v5/em-v50/estep-r3`, `em-v51/kl-r4`, Pruefmenge `welt_v5/pruef`); in Git nur Code und Summen. diff --git a/messung/motor/poolgegner_tafel/aggregat.py b/messung/motor/poolgegner_tafel/aggregat.py new file mode 100644 index 00000000..3a6f8ab1 --- /dev/null +++ b/messung/motor/poolgegner_tafel/aggregat.py @@ -0,0 +1,102 @@ +# Pool opponent table: reads the E-step outputs on the SSD (posterior-weighted sums, no hand or player ids) and aggregates them per node: +# variants (type, legal mask, o) with mass, and observed-action counts per q bin (post-flop) or per start-hand class (preflop, with the mean q of the class). +# Post-flop source: welt_v5/em-v50/estep-r3/*.estep.jsonl.gz (E-step of the v5.0 round-3 parameters, 15 days; post-flop parameters are frozen from v5.0 on). +# Preflop source: welt_v5/em-v51/kl-r4/*.kl (E-step of v5.1, all 52 learning days, `klassen_daten` format). +import sys, os; sys.dont_write_bytecode = True +import glob, gzip, json +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import knoten as KN # noqa: E402 +import klassen_daten as KD # noqa: E402 + +BINS = 20 +NA = 6 +O_STELLEN = 3 + + +def _variante_key(typ, erl, o): + return (int(typ), tuple(int(x) for x in erl), tuple(round(float(x), O_STELLEN) for x in o)) + + +def _merge_var(ziel, quelle): + for k, m in quelle.items(): + ziel[k] = ziel.get(k, 0.0) + m + + +def datei_nachflop(pfad): + """One E-step file -> {code: {"var": {key: mass}, "na": [20, 6]}} for post-flop decisions (street > 0).""" + out = {} + opener = gzip.open if pfad.endswith(".gz") else open + with opener(pfad, "rt", encoding="utf-8") as f: + for z in f: + if '"st":0' in z and '"st":1' not in z and '"st":2' not in z and '"st":3' not in z: + continue + h = json.loads(z) + for e in h.get("ents") or (): + if e["st"] == 0: + continue + typ = e["typen"][0][0] + w = np.fromiter((b[0] for b in e["bins"]), float, count=BINS) + m = float(w.sum()) + if m <= 0: + continue + c = int(e["codes"][0]) + d = out.get(c) + if d is None: + d = out[c] = {"var": {}, "na": np.zeros((BINS, NA))} + k = _variante_key(typ, e["erlaubt"], e["o"]) + d["var"][k] = d["var"].get(k, 0.0) + m + d["na"][:, int(e["zug"])] += w + return out + + +def aggregiere_nachflop(pfade, prozesse=2): + """-> {code: {"varianten": [{typ, erl, o, masse}], "na": [20, 6]}}""" + if prozesse > 1 and len(pfade) > 1: + import multiprocessing as mp + with mp.get_context("spawn").Pool(prozesse) as pool: + teile = pool.map(datei_nachflop, pfade) + else: + teile = [datei_nachflop(p) for p in pfade] + ges = {} + for t in teile: + for c, d in t.items(): + g = ges.setdefault(c, {"var": {}, "na": np.zeros((BINS, NA))}) + _merge_var(g["var"], d["var"]); g["na"] += d["na"] + return {c: {"varianten": [{"typ": k[0], "erl": list(k[1]), "o": list(k[2]), "masse": m} for k, m in d["var"].items()], "na": d["na"]} for c, d in ges.items()} + + +def aggregiere_vorflop(pfade): + """KL files (one per day) -> {code: {"varianten", "na": [169, 6], "qbar": [169]}}. Cell mass W includes the type posterior; na[code, class, observed action] += W; qbar = sum WQ / sum W.""" + var = {}; na = {}; wq = {}; ww = {} + for p in pfade: + meta, (W, WQ, _) = KD.lese_roh(p) + for i in range(len(meta)): + c = int(meta["code"][i]); z = int(meta["zug"][i]); erl = [(int(meta["erl"][i]) >> a) & 1 for a in range(NA)] + w = W[i].astype(np.float64) + m = float(w.sum()) + if m <= 0: + continue + d = var.setdefault(c, {}) + k = _variante_key(meta["typ"][i], erl, meta["o"][i]) + d[k] = d.get(k, 0.0) + m + if c not in na: + na[c] = np.zeros((KD.NK, NA)); wq[c] = np.zeros(KD.NK); ww[c] = np.zeros(KD.NK) + na[c][:, z] += w; wq[c] += WQ[i]; ww[c] += w + out = {} + for c, d in var.items(): + with np.errstate(invalid="ignore", divide="ignore"): + qbar = np.where(ww[c] > 0, wq[c] / np.where(ww[c] > 0, ww[c], 1.0), np.nan) + out[c] = {"varianten": [{"typ": k[0], "erl": list(k[1]), "o": list(k[2]), "masse": m} for k, m in d.items()], "na": na[c], "qbar": qbar} + return out + + +def pfade_nachflop(wurzel): + return sorted(glob.glob(os.path.join(wurzel, "em-v50", "estep-r3", "*.estep.jsonl.gz"))) + + +def pfade_vorflop(wurzel): + return sorted(glob.glob(os.path.join(wurzel, "em-v51", "kl-r4", "*.kl"))) diff --git a/messung/motor/poolgegner_tafel/auswerten.py b/messung/motor/poolgegner_tafel/auswerten.py new file mode 100644 index 00000000..0486f86d --- /dev/null +++ b/messung/motor/poolgegner_tafel/auswerten.py @@ -0,0 +1,171 @@ +# Pool opponent table: statistics of the held-out run (bewerten.py output) -> tables A (log loss vs baselines), B (PIT), C (cell support) and the verdict per street. +# python3 auswerten.py +# Bootstrap: resampling PLAYERS (multinomial weights over the player ids of the held-out hands), 2000 draws, 95 % percentile interval. +# Verdict rule (fixed before the run, KARTE.md): "traegt" if gain over frequency AND over uniform have lower bound > 0, |mean PIT - 0.5| < 0.03 (shown hands) and at most 10 % of +# the decision mass sits in cells with n < 50; "traegt nur mit Vertrauensgewicht" if both gains are > 0 (point estimate) but a further condition fails or a lower bound is <= 0; +# "traegt nicht" if the gain over uniform or over frequency is <= 0 (point estimate). +import sys, os; sys.dont_write_bytecode = True +import json +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HIER) +import bewerten as BW # noqa: E402 + +B = 2000 +STRASSEN = BW.STRASSEN +AKTIONEN = ("check", "call", "bet/raise", "jam", "fold") + + +def aktion_von(zug, gegen_offen): + if zug == 0: + return "fold" + if zug == 1: + return "call" if gegen_offen else "check" + return "jam" if zug == 5 else "bet/raise" + + +def boot_gain(pid_idx, n_p, s_p, rng, w_list=None): + """Bootstrap of sum(s)/sum(n) over players; s_p [P, k] -> (point [k], lo [k], hi [k]).""" + P = len(n_p) + pt = s_p.sum(0) / max(n_p.sum(), 1) + est = np.empty((B, s_p.shape[1])) + for b0 in range(0, B, 200): + W = rng.multinomial(P, np.full(P, 1.0 / P), size=min(200, B - b0)).astype(float) + est[b0:b0 + 200] = (W @ s_p) / np.maximum(W @ n_p, 1)[:, None] + return pt, np.percentile(est, 2.5, axis=0), np.percentile(est, 97.5, axis=0) + + +def tabelle_a(D, rng): + cl = {c: BW.klasse_von(c) for c in np.unique(D["code"])} + klasse = np.array([cl[c] for c in D["code"]]) + pid = D["pid"] + _, pidx = np.unique(pid, return_inverse=True) + P = pidx.max() + 1 + rows = [] + sel_alle = [("alle", np.ones(len(pid), bool))] + sel_str = [(STRASSEN[s], D["st"] == s) for s in range(4)] + sel_kl = [(STRASSEN[int(D["st"][klasse == k][0])] + " | " + k, klasse == k) for k in sorted(set(klasse.tolist()))] + for name, m in sel_alle + sel_str + sel_kl: + n = int(m.sum()) + if n < 30: + continue + cols = np.stack([D["ll_freq"] - D["ll_tafel"], D["ll_unif"] - D["ll_tafel"], D["ll_tafel"], D["ll_freq"], D["ll_unif"], D["sh10"], D["sh50"], D["sh200"], D["aufg"].astype(float), D["leer"].astype(float), D["floor"], + D["ll_freq"] - D["ll_schrumpf"], D["ll_freq"] - D["ll_kal"], D["ll_unif"] - D["ll_kal"], D["ll_kal"], D["maske_aus"]], 1) + n_p = np.bincount(pidx[m], minlength=P).astype(float) + s_p = np.stack([np.bincount(pidx[m], weights=cols[m, j], minlength=P) for j in range(cols.shape[1])], 1) + pt, lo, hi = boot_gain(pidx[m], n_p, s_p, rng) + rows.append({"auswahl": name, "n": n, "spieler": int((n_p > 0).sum()), + "gewinn_gegen_haeufigkeit": [pt[0], lo[0], hi[0]], "gewinn_gegen_gleich": [pt[1], lo[1], hi[1]], + "ll_tafel": pt[2], "ll_haeufigkeit": pt[3], "ll_gleich": pt[4], + "anteil_n_unter_10": pt[5], "anteil_n_unter_50": pt[6], "anteil_n_unter_200": pt[7], "anteil_aufgefuellt": pt[8], "anteil_leer": pt[9], "anteil_boden": pt[10], + "gewinn_schrumpf_gegen_haeufigkeit": [pt[11], lo[11], hi[11]], "gewinn_kal_gegen_haeufigkeit": [pt[12], lo[12], hi[12]], "gewinn_kal_gegen_gleich": [pt[13], lo[13], hi[13]], "ll_kal": pt[14], "anteil_maske_ausserhalb": pt[15]}) + return rows + + +def tabelle_b(Pt, D, rng): + """PIT of the true hand in the model's range after its action. Rows: shown (muck 0) and mucked river hands (muck 1, weight spread by posterior over the beaten hands).""" + cl = {c: BW.klasse_von(c) for c in np.unique(Pt["code"])} if len(Pt["code"]) else {} + gegen = {c: (not cl[c].endswith("offen")) for c in cl} + akt = np.array([aktion_von(int(z), gegen[c]) for z, c in zip(Pt["zug"], Pt["code"])]) + out = [] + pid = Pt["pid"]; _, pidx = np.unique(pid, return_inverse=True); Pn = pidx.max() + 1 if len(pid) else 0 + def stat(m, name): + if m.sum() < 20: + return None + w = Pt["gewicht"][m]; x = Pt["pit"][m] + n_p = np.bincount(pidx[m], weights=w, minlength=Pn) + s_p = np.stack([np.bincount(pidx[m], weights=w * x, minlength=Pn), np.bincount(pidx[m], weights=w * np.abs(x - 0.5), minlength=Pn)], 1) + pt, lo, hi = boot_gain(pidx[m], n_p, s_p, rng) + h = np.bincount(np.minimum((x * 10).astype(int), 9), weights=w, minlength=10); h = h / h.sum() + cdf = np.cumsum(h); ks = float(np.abs(cdf - np.arange(1, 11) / 10).max()) + return {"auswahl": name, "n": float(w.sum()), "mittleres_PIT": [pt[0], lo[0], hi[0]], "mittlerer_abstand_von_0,5": [pt[1], lo[1], hi[1]], "ks_10bins": ks, "hist10": h.tolist()} + for s in range(4): + for quelle, mk in (("gezeigt", 0), ("gezeigt+gemuckt", None)): + m = (Pt["st"] == s) & ((Pt["muck"] == 0) if mk == 0 else np.ones(len(pid), bool)) + r = stat(m, "%s | %s" % (STRASSEN[s], quelle)) + if r: out.append(r) + for a in AKTIONEN: + m = (Pt["st"] == s) & (Pt["muck"] == 0) & (akt == a) + r = stat(m, "%s | gezeigt | %s" % (STRASSEN[s], a)) + if r: out.append(r) + return out + + +def tabelle_d(Cd, rng): + """Strength axis, conditional: -log P(observed class | TRUE shown hand) (table row of the hand, range before the decision) against the node frequency and uniform; shown hands only. + *_eps = (1 - 0.01) P(a|h) + 0.01 P(a) as in the Messlatte; plain = floor 1e-4. Selection: shown hands = hands that reached showdown.""" + _, pidx = np.unique(Cd["pid"], return_inverse=True); P = pidx.max() + 1 + rows = [] + for name, m in [("alle", np.ones(len(pidx), bool))] + [(STRASSEN[s], Cd["st"] == s) for s in range(4)]: + if m.sum() < 30: + continue + cols = np.stack([Cd["ll_freq"] - Cd["ll_p_eps"], Cd["ll_freq"] - Cd["ll_kal_eps"], Cd["ll_freq"] - Cd["ll_schr_eps"], Cd["ll_unif"] - Cd["ll_p_eps"], + Cd["ll_freq"] - Cd["ll_p"], Cd["ll_freq"] - Cd["ll_kal"], Cd["ll_freq"] - Cd["ll_schr"], Cd["ll_p_eps"], Cd["ll_freq"]], 1) + n_p = np.bincount(pidx[m], minlength=P).astype(float) + s_p = np.stack([np.bincount(pidx[m], weights=cols[m, j], minlength=P) for j in range(cols.shape[1])], 1) + pt, lo, hi = boot_gain(pidx[m], n_p, s_p, rng) + rows.append({"auswahl": name, "n": int(m.sum()), "gewinn_p_eps": [pt[0], lo[0], hi[0]], "gewinn_kal_eps": [pt[1], lo[1], hi[1]], "gewinn_schrumpf_eps": [pt[2], lo[2], hi[2]], "gewinn_p_eps_gegen_gleich": [pt[3], lo[3], hi[3]], + "gewinn_p_roh": [pt[4], lo[4], hi[4]], "gewinn_kal_roh": [pt[5], lo[5], hi[5]], "gewinn_schrumpf_roh": [pt[6], lo[6], hi[6]], "ll_p_eps": pt[7], "ll_freq": pt[8]}) + return rows + + +def verdikt(a_rows, b_rows, variante="p"): + out = {} + for s in range(4): + r = next((x for x in a_rows if x["auswahl"] == STRASSEN[s]), None) + b = next((x for x in b_rows if x["auswahl"] == "%s | gezeigt" % STRASSEN[s]), None) + if r is None: + out[STRASSEN[s]] = {"urteil": "keine Daten"}; continue + gf, gu = (r["gewinn_gegen_haeufigkeit"], r["gewinn_gegen_gleich"]) if variante == "p" else (r["gewinn_kal_gegen_haeufigkeit"], r["gewinn_kal_gegen_gleich"]) + pit_ok = b is not None and abs(b["mittleres_PIT"][0] - 0.5) < 0.03 + klein_ok = r["anteil_n_unter_50"] <= 0.10 + if gf[1] > 0 and gu[1] > 0 and pit_ok and klein_ok: + u = "traegt als Trainingsgegner" + elif gf[0] > 0 and gu[0] > 0: + u = "traegt nur mit Vertrauensgewicht" + else: + u = "traegt nicht" + out[STRASSEN[s]] = {"urteil": u, "gewinn_haeufigkeit": gf, "gewinn_gleich": gu, "PIT_mittel": b["mittleres_PIT"] if b else None, "PIT_ok": bool(pit_ok), "anteil_n_unter_50": r["anteil_n_unter_50"], "klein_ok": bool(klein_ok)} + return out + + +def md(a_rows, b_rows, v, d_rows=()): + z = ["## A) log loss per decision (nats, lower = better); gain = baseline - table, 95 % bootstrap over players", "", + "| selection | n | table p | freq | uniform | gain p vs freq | gain p vs uniform | gain p_schrumpf vs freq | gain p_kal vs freq | gain p_kal vs uniform |", "|---|---|---|---|---|---|---|---|---|---|"] + f = lambda t: "%+.4f [%+.4f; %+.4f]" % tuple(t) + for r in a_rows: + z.append("| %s | %d | %.4f | %.4f | %.4f | %s | %s | %s | %s | %s |" % (r["auswahl"], r["n"], r["ll_tafel"], r["ll_haeufigkeit"], r["ll_gleich"], f(r["gewinn_gegen_haeufigkeit"]), f(r["gewinn_gegen_gleich"]), + f(r["gewinn_schrumpf_gegen_haeufigkeit"]), f(r["gewinn_kal_gegen_haeufigkeit"]), f(r["gewinn_kal_gegen_gleich"]))) + z += ["", "## C) support: share of decision mass (range mass) in cells with small n, and flagged cells", "", "| selection | n<10 | n<50 | n<200 | aufgefuellt | leer (no alpha) | floor hits | mask outside typical |", "|---|---|---|---|---|---|---|---|"] + for r in a_rows: + z.append("| %s | %.3f | %.3f | %.3f | %.3f | %.3f | %.4f | %.4f |" % (r["auswahl"], r["anteil_n_unter_10"], r["anteil_n_unter_50"], r["anteil_n_unter_200"], r["anteil_aufgefuellt"], r["anteil_leer"], r["anteil_boden"], r["anteil_maske_ausserhalb"])) + z += ["", "## B) PIT of the true hand in the model range after its action (uniform = calibrated; mean 0.5, mean |PIT-0.5| = 0.25)", "", "| selection | n | mean PIT | mean abs dist | KS(10 bins) |", "|---|---|---|---|---|"] + for r in b_rows: + z.append("| %s | %.0f | %s | %s | %.3f |" % (r["auswahl"], r["n"], "%.3f [%.3f; %.3f]" % tuple(r["mittleres_PIT"]), "%.3f [%.3f; %.3f]" % tuple(r["mittlerer_abstand_von_0,5"]), r["ks_10bins"])) + z += ["", "## D) strength axis, conditional on the TRUE shown hand: gain over node frequency in nats (eps = 0.01 mix as Messlatte | plain floor 1e-4)", "", + "| selection | n | p (eps) | p_kal (eps) | p_schrumpf (eps) | p vs uniform (eps) | p plain | p_kal plain | p_schrumpf plain |", "|---|---|---|---|---|---|---|---|---|"] + for r in d_rows: + z.append("| %s | %d | %s | %s | %s | %s | %s | %s | %s |" % (r["auswahl"], r["n"], f(r["gewinn_p_eps"]), f(r["gewinn_kal_eps"]), f(r["gewinn_schrumpf_eps"]), f(r["gewinn_p_eps_gegen_gleich"]), + f(r["gewinn_p_roh"]), f(r["gewinn_kal_roh"]), f(r["gewinn_schrumpf_roh"]))) + z += ["", "## Verdict per street (variant p = model as exported; p_kal = node-marginal recalibrated)", ""] + ["- %s: p: %s | p_kal: %s" % (k, x["urteil"], v["p_kal"][k]["urteil"]) for k, x in v["p"].items()] + return "\n".join(z) + "\n" + + +def main(argv): + src, aus = argv[1:3] + if os.path.exists(aus): + sys.exit("exists, never overwritten: %s" % aus) + D = dict(np.load(os.path.join(src, "entscheidungen.npz"))); Pt = dict(np.load(os.path.join(src, "pit.npz"))) + rng = np.random.RandomState(20261205) + Cd = dict(np.load(os.path.join(src, "bedingt.npz"))) + a = tabelle_a(D, rng); b = tabelle_b(Pt, D, rng); d = tabelle_d(Cd, rng); v = {"p": verdikt(a, b, "p"), "p_kal": verdikt(a, b, "p_kal")} + tmp = aus + ".tmp"; os.makedirs(tmp) + json.dump({"A": a, "B": b, "D": d, "verdikt": v}, open(os.path.join(tmp, "ergebnis.json"), "w"), indent=1) + open(os.path.join(tmp, "ergebnis.md"), "w").write(md(a, b, v, d)) + os.rename(tmp, aus) + print(md(a, b, v, d)) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/messung/motor/poolgegner_tafel/bauen.py b/messung/motor/poolgegner_tafel/bauen.py new file mode 100644 index 00000000..df937f6a --- /dev/null +++ b/messung/motor/poolgegner_tafel/bauen.py @@ -0,0 +1,169 @@ +# Pool opponent table: build. Reads model parameters + E-step aggregates, builds the table, writes it atomically (never overwrites). +# nice -n 15 python3 bauen.py --aus "" [--nachflop-tage N] [--zusatz meta-zusatz.json ...] +# Sources (SSD, not in Git): welt_v5/em-v50/estep-r3 (post-flop), welt_v5/em-v51/kl-r4 (preflop). Parameters: welt_v5/parameter/v5.1-gegenuns.json (= v5.1-r4 + delta). +import sys, os; sys.dont_write_bytecode = True +import argparse, gzip, hashlib, json, math, subprocess, time +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, HIER); sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import kern as KE # noqa: E402 +import aggregat as AG # noqa: E402 +import schreiben as SC # noqa: E402 +import messlatte as ML # noqa: E402 +import staerke as ST # noqa: E402 +import gamma as GA # noqa: E402 + +WURZEL = "/Volumes/Alpha SSD/pokerfreak-daten/welt_v5" +PARAMETER = os.path.join(V5, "parameter", "v5.1-gegenuns.json") +PARAMETER_BASIS = os.path.join(V5, "parameter", "v5.1-r4.json") +WELT = os.path.join(V5, "..", "welt_v4", "welt_v4.json.gz") +LIVE_FEIN = "/Volumes/Alpha SSD/pokerfreak-daten/pruefstand/antwort-eichung-live/zellen-fein.json" +STUFE1 = os.path.join(V5, "live", "ergebnisse", "stufe1-tafeln.json") +BIS = (0.45, 0.85, 1.3, 99.0) # live answer table bands (v2/v3 rows) <-> node gegen 1..4 + + +def sha(pfad): + h = hashlib.sha256() + with open(pfad, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def wilson(k, n, z=1.96): + if n <= 0: + return (float("nan"), float("nan")) + p = k / n; d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d; h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d + return (c - h, c + h) + + +def groessen(welt_limit): + """Size distributions (counts and probabilities) from the world file, with the bin definitions.""" + L = welt_limit + gs = L["groessen_stufen"]; gm = L["vielfach_stufen"] + nf = np.array(L["groessen_nach_flop"], float) + vf = np.array(L["vielfache_vorflop"], float) + nrm = lambda a: (a / np.maximum(a.sum(-1, keepdims=True), 1e-300)).tolist() + return { + "nachflop": {"stufen": int(gs[0]), "unten": gs[1], "oben": gs[2], "einheit": "bet / pot-after-call, log-spaced steps between unten and oben", + "achsen": "[street 0..3 (index 1..3 used)][art 0 bet | 1 raise][class j 0..3 = bet band k m g u][step]", + "p": nrm(nf), "n": nf.sum(-1).tolist(), "allin": {"achsen": "[street][art][j][stack band 0..6 (kanten stapel_kanten)] = [n not all-in, n all-in]", "n": L["allin_nach_flop"]}, + "stapel_kanten": L["stapel_kanten"]}, + "vorflop": {"stufen": int(gm[0]), "unten": gm[1], "oben": gm[2], "einheit": "raise-to as multiple of the current high bet (h_eff), log-spaced steps", "achsen": "[lage 0..4][step]", + "p": nrm(vf), "n": vf.sum(-1).tolist(), "allin": {"achsen": "[lage][fach 0..5][stack band 0..4 (vf_stapel_kanten)] = [n not all-in, n all-in]", "n": L["allin_vorflop"]}, + "vf_stapel_kanten": L["vf_stapel_kanten"]}, + "regel": "Welt.groesse: pick all-in share first, then a step by weight, clip to [min, max] of the legal range, uniform in log inside the step; not conditional on q", + } + + +def live_tabelle(): + """Live fold counts against OUR bets per (street, band, position): from the live answer cell table (summed over type and line).""" + z = json.load(open(LIVE_FEIN)) + acc = {} + for c in z: + k = (int(c["strasse"]), float(c["bis"]), c["position"]) + a = acc.setdefault(k, [0, 0, 0.0]) + a[0] += c["fold"]; a[1] += c["n"]; a[2] += c["v5_fold"] * c["n"] + out = [] + for (s, bis, pos), (k, n, v5) in sorted(acc.items()): + lo, hi = wilson(k, n) + out.append({"strasse": s, "bis": bis, "position_wir": pos, "live_k": k, "live_n": n, "lo": lo, "hi": hi, "v5_fold_mittel": v5 / n}) + return out + + +def stufe1_zeilen(): + d = json.load(open(STUFE1)) + keep = ("zelle", "ereignis", "n", "live", "lo", "hi", "haeufigkeit", "v5", "v4") + return [{k: z[k] for k in keep if k in z} for z in d["zellen"] if z.get("n")] + + +def live_spalten(T, codes, tab): + """Per-node live cross-check columns for post-flop nodes that face a bet (gegen 1..4) on turn/river: live k, n, Wilson interval, model fold (q-marginal) with and without the delta.""" + import knoten as KN + N = len(codes) + A = {"gegen_live_k": np.zeros((1, N)), "gegen_live_n": np.zeros((1, N)), "gegen_live_lo": np.full((1, N), np.nan), "gegen_live_hi": np.full((1, N), np.nan), + "gegen_modell_fold": np.full((1, N), np.nan), "gegen_modell_fold_gegenuns": np.full((1, N), np.nan), "bekanntes_fehl": np.zeros((1, N), bool)} + live = {(z["strasse"], z["bis"], z["position_wir"]): z for z in tab} + for i, c in enumerate(codes): + t = KN.teile(int(c)) + if t["vorflop"]: + continue + g = t["gegen"] + n = T["n"][0, i]; w = n / n.sum() if n.sum() > 0 else np.full(KE.BINS, 1.0 / KE.BINS) + if 1 <= g <= 4: + A["gegen_modell_fold"][0, i] = float((w * T["p"][0, i, :, 0]).sum()) + A["gegen_modell_fold_gegenuns"][0, i] = float((w * T["p_gegenuns"][0, i, :, 0]).sum()) + if t["st"] >= 1: + z = live.get((1 + t["st"], BIS[g - 1], "oop" if t["ip"] else "ip")) + if z: + A["gegen_live_k"][0, i] = z["live_k"]; A["gegen_live_n"][0, i] = z["live_n"]; A["gegen_live_lo"][0, i] = z["lo"]; A["gegen_live_hi"][0, i] = z["hi"] + if t["st"] == 2 and g == 1: + A["bekanntes_fehl"][0, i] = True # river, bet < 0.45 pot: small leads <= 25 % and 25-50 % without position (STUFE1.md); cannot be split at node level + return A + + +def git_stand(): + try: + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=HIER, text=True).strip() + except Exception: + return None + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--aus", required=True) + ap.add_argument("--nachflop-tage", type=int, default=0, help="0 = all stored days") + ap.add_argument("--zusatz", nargs="*", default=[], help="JSON files merged into meta (e.g. modellwahl, held-out result)") + ap.add_argument("--prozesse", type=int, default=2) + a = ap.parse_args(argv) + if os.path.exists(a.aus): + sys.exit("exists, never overwritten: %s" % a.aus) + t0 = time.time() + with open(PARAMETER, encoding="utf-8") as f: + p = json.load(f) + modell = ML.V5Modell(p, ST.vorflop_staerke(p["vorflop"])) + with gzip.open(WELT, "rb") as f: + welt = json.loads(f.read().decode("utf-8")) + L = min(welt["limits"], key=lambda x: abs(math.log(x["bb"] / 0.02))) + bb = float(L["bb"]) + pf = AG.pfade_nachflop(WURZEL) + if a.nachflop_tage: + pf = pf[:a.nachflop_tage] + kl = AG.pfade_vorflop(WURZEL) + print("post-flop files %d, preflop files %d" % (len(pf), len(kl)), flush=True) + dn = AG.aggregiere_nachflop(pf, a.prozesse); print("post-flop aggregated: %d nodes (%.0f s)" % (len(dn), time.time() - t0), flush=True) + dv = AG.aggregiere_vorflop(kl); print("preflop aggregated: %d nodes (%.0f s)" % (len(dv), time.time() - t0), flush=True) + N = KE.bauen_nachflop(modell, dn, bb, mit_gegenuns=True); print("post-flop built (%.0f s)" % (time.time() - t0), flush=True) + V = KE.bauen_vorflop(modell, dv, bb, mit_gegenuns=True); print("preflop built (%.0f s)" % (time.time() - t0), flush=True) + tab = live_tabelle() + N.update(live_spalten(N, N["code"], tab)) + meta = { + "format": "poolgegner-tafel-v1", "gebaut": time.strftime("%Y-%m-%d %H:%M:%S"), "git": git_stand(), + "limit": {"bb": [bb], "bemerkung": "axis 0 = limit; only NL2 is filled; no limit-specific code; lambda (log2 bb/0.02 term) below"}, + "typ": "pool = mixture of the 48 types + pseudo type -1 by posterior mass at the node; per-type tables not exported", + "quellen": {"parameter": {"datei": "welt_v5/parameter/v5.1-gegenuns.json", "sha256": sha(PARAMETER), "fassung": p["fassung"]}, + "parameter_basis": {"datei": "welt_v5/parameter/v5.1-r4.json", "sha256": sha(PARAMETER_BASIS)}, + "welt": {"datei": "welt_v4/welt_v4.json.gz", "sha256": sha(WELT)}, + "nachflop": {"quelle": "welt_v5/em-v50/estep-r3 (E-step, 15 days; post-flop parameters frozen from v5.0)", "dateien": len(pf)}, + "vorflop": {"quelle": "welt_v5/em-v51/kl-r4 (E-step v5.1, all learning days)", "dateien": len(kl)}}, + "lambda": modell.lam.tolist(), "klassen": GA.KLASSEN, "vorflop_staerke": [p["vorflop"][k] for k in GA.KLASSEN] if isinstance(p["vorflop"], dict) else p["vorflop"], + "gegenuns": {"delta": modell.gegen.delta.tolist(), "regel": "u_a += delta[street][band][pos][call|raise] when the opponent faces a bet/raise of the trained player (gegenuns.zelle)"}, + "kappa": {"nachflop": N["kappa_tabelle"], "vorflop": V["kappa_tabelle"], "marginal": {"nachflop": N["kappa_marginal"], "vorflop": V["kappa_marginal"]}, "methode": "Beta-binomial moments, antworttafel_v3.kappa, group (street, fallback level), cells with n >= 2, classes with 0 < p < 1 pooled; inf = no over-dispersion"}, + "groessen": groessen(L), "gegenuns_live": tab, "stufe1_live": stufe1_zeilen(), + "q": {"bins": KE.BINS, "regel": "see FORMAT.md section 3", "stufen": list(KE.STUFEN_NAMEN)}, + "zaehlung": {"nachflop_knoten": int(len(N["code"])), "nachflop_knoten_mit_daten": int((N["n_knoten"] > 0).sum()), "vorflop_knoten": int(len(V["code"])), "vorflop_knoten_mit_daten": int((V["n_knoten"] > 0).sum()), + "n_nachflop": float(N["n_knoten"].sum()), "n_vorflop": float(V["n_knoten"].sum())}, + } + for z in a.zusatz: + with open(z) as f: + meta.update(json.load(f)) + extra = [os.path.join(HIER, "lesen.py")] + [os.path.join(HIER, "FORMAT.md")] if os.path.exists(os.path.join(HIER, "FORMAT.md")) else [os.path.join(HIER, "lesen.py")] + SC.schreibe_tafel(a.aus, {"nachflop": N, "vorflop": V}, meta, dateien=extra) + print("written", a.aus, "(%.0f s)" % (time.time() - t0)) + + +if __name__ == "__main__": + main() diff --git a/messung/motor/poolgegner_tafel/bewerten.py b/messung/motor/poolgegner_tafel/bewerten.py new file mode 100644 index 00000000..dea8f870 --- /dev/null +++ b/messung/motor/poolgegner_tafel/bewerten.py @@ -0,0 +1,191 @@ +# Pool opponent table: held-out evaluation, reading the table EXACTLY as a trainer would (lesen.Tafel: forward range -> q -> bin -> p, mask renormalised, pool without type). +# Held-out set: Welt v5 held-out hands (welt_v5/pruef: 50.000 hands with t >= 2026-07-22, 113 days, disjoint from the learning days before 22.07.); optional every-N-th hand. +# A) log loss per decision (predictive probability of the observed class, forward range marginal) by street x node class vs (a) per-node frequency without hand strength, (b) uniform over legal +# B) strength axis: PIT of the true (shown) hand in the model's range after its action, by street / action class; selection bias from mucks (E-step style evidence) quantified +# C) per-cell n: share of decision mass in cells with n < 10 / 50 / 200 and in cells flagged aufgefuellt +# python3 bewerten.py --tafel --aus [--jede 5] [--prozesse 2] +import sys, os; sys.dont_write_bytecode = True +import argparse, gzip, json, time, zlib +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, HIER); sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import lesen as LE # noqa: E402 +import messlatte as ML # noqa: E402 +import staerke as ST # noqa: E402 +import gamma as GA # noqa: E402 +import knoten as KN # noqa: E402 + +PRUEF = "/Volumes/Alpha SSD/pokerfreak-daten/welt_v5/pruef" +PARAMETER = os.path.join(V5, "parameter", "v5.1-gegenuns.json") +FLOOR = 1e-4 +VARIANTEN = ("p", "p_schrumpf", "p_kal") +N_MIN = 20 +SCHWELLEN = (10, 50, 200) +GEGEN_NAMEN = ("offen", "vs-klein", "vs-mittel", "vs-gross", "vs-over", "vs-raise") +LAGE_NAMEN = ("offen", "limp", "vs-open", "vs-3bet", "vs-4bet") +STRASSEN = ("Vorflop", "Flop", "Turn", "River") + + +def klasse_von(code): + t = KN.teile(int(code)) + return ("VF " + LAGE_NAMEN[t["lage"]]) if t["vorflop"] else (STRASSEN[1 + t["st"]] + " " + GEGEN_NAMEN[t["gegen"]]) + + +class Haeufigkeit: + """Per-node action frequency without hand strength, from the table's own counts (fine -> medium -> coarse -> uniform over legal).""" + + def __init__(self, tafel): + self.f = {} + import knoten as K + for teil in ("nachflop", "vorflop"): + t = getattr(tafel, teil) + na = np.asarray(t["na"][0], float) # [N, B|169, 6] + s = na.sum(1) + for i, c in enumerate(np.asarray(t["code"])): + self.f[(0, int(c))] = s[i] + for lvl in (1, 2): + for i, c in enumerate(np.asarray(t["code"])): + k = (lvl, K.hoch(int(c), lvl)) + self.f[k] = (self.f[k] + s[i]) if k in self.f else s[i].copy() + + def p(self, codes, erlaubt): + m = np.asarray(erlaubt, float) + for lvl in (0, 1, 2): + v = self.f.get((lvl, int(codes[lvl]))) + if v is not None and v.sum() >= N_MIN: + x = (v + 0.1) * m + return x / x.sum() + return m / m.sum() + + +def tag_worker(args): + tag, tafel_pfad, jede, nur_pit = args + tafel = LE.Tafel.lade(tafel_pfad, mmap=False) + with open(PARAMETER, encoding="utf-8") as f: + par = json.load(f) + modell = ML.V5Modell(par, ST.vorflop_staerke(par["vorflop"])) + freq = Haeufigkeit(tafel) + roh = {} + with gzip.open(os.path.join(PRUEF, "roh", tag + ".jsonl.gz"), "rt") as f: + for z in f: + h = json.loads(z) + roh[str(h["h"])] = [s.get("id") for s in h["s"]] + D = []; P = []; C = [] # decision rows, PIT rows + nt = tafel.nachflop["n"][0]; nv = tafel.vorflop["n"][0] + ixn = tafel._idx["nachflop"]; ixv = tafel._idx["vorflop"] + kmap = GA.KLASSE_VON_KOMBI + with gzip.open(os.path.join(PRUEF, "entscheidungen", tag + ".entscheidungen.jsonl.gz"), "rt") as f: + for nr, z in enumerate(f): + if nr % jede: + continue + h = json.loads(z) + brett = h["brett"] + ids = roh.get(str(h["h"])) + if ids is None: + continue + live = ML.lebende(brett, []).astype(float) + sv = {} + for sp in h["spieler"]: + if not sp["ents"]: + continue + pid = int((ids[sp["platz"]] or "0")[:12], 16) + w = live.copy() + wv = {v: live.copy() for v in VARIANTEN[1:]} + for e in sp["ents"]: + st = e["st"]; code = e["codes"][0]; erl = e["erlaubt"]; zug = e["zug"] + if st not in sv: + sv[st] = modell.staerke(st, brett) + m0 = tafel.zaehler["maske_ausserhalb"] + try: + if st == 0: + Pm, q = tafel.verteilung_vorflop(code, kmap, erl) + n_zelle = np.asarray(nv[ixv[code]])[kmap] + aufg = bool(tafel.vorflop["aufgefuellt"][0, ixv[code]]); leer = bool(tafel.vorflop["aufgefuellt_leer"][0, ixv[code]]) + nkn = float(nv[ixv[code]].sum()) + else: + Pm, q = tafel.verteilung(code, w, sv[st], erl) + b = LE.bin_von(q) + n_zelle = np.asarray(nt[ixn[code]])[b] + aufg = bool(tafel.nachflop["aufgefuellt"][0, ixn[code]]); leer = bool(tafel.nachflop["aufgefuellt_leer"][0, ixn[code]]) + nkn = float(nt[ixn[code]].sum()) + except KeyError: + continue + ms = w.sum() + dmask = tafel.zaehler["maske_ausserhalb"] - m0 + pred = (w[:, None] * Pm).sum(0) / ms + llv = [] + hk = ST.kombi_nr(int(sp["gezeigt"][0]), int(sp["gezeigt"][1])) if sp["gezeigt"] is not None else None + pc = {"p": (Pm[hk, zug], pred[zug])} if hk is not None else None + for v in VARIANTEN[1:]: + if st == 0: + Pv, _ = tafel.verteilung_vorflop(code, kmap, erl, variante=v) + else: + Pv, _ = tafel.verteilung(code, wv[v], sv[st], erl, variante=v) + pv = (wv[v][:, None] * Pv).sum(0) / wv[v].sum() + llv.append(-np.log(max(pv[zug], FLOOR))) + if pc is not None: + pc[v] = (Pv[hk, zug], pv[zug]) + wv[v] = LE.fortschreiben(wv[v], Pv, zug) + pf = freq.p(e["codes"], erl) + pu = np.asarray(erl, float) / sum(erl) + sh = [(w * (n_zelle < t)).sum() / ms for t in SCHWELLEN] + D.append((pid, st, int(code), zug, -np.log(max(pred[zug], FLOOR)), -np.log(max(pf[zug], FLOOR)), -np.log(max(pu[zug], FLOOR)), sh[0], sh[1], sh[2], aufg, leer, nkn, + float(pred[zug] < FLOOR), llv[0], llv[1], float(dmask > 0))) + if pc is not None: + eps = 0.01 + f_ = lambda x: -np.log(max(x, FLOOR)) + C.append((pid, st, int(code), zug, f_(pc["p"][0]), f_((1 - eps) * pc["p"][0] + eps * pc["p"][1]), f_(pc["p_kal"][0]), f_((1 - eps) * pc["p_kal"][0] + eps * pc["p_kal"][1]), + f_(pc["p_schrumpf"][0]), f_((1 - eps) * pc["p_schrumpf"][0] + eps * pc["p_schrumpf"][1]), f_(pf[zug]), f_(pu[zug]))) + w = LE.fortschreiben(w, Pm, zug) + # B) PIT: the true hand's quantile in the range after its action + if sp["gezeigt"] is not None: + hk = ST.kombi_nr(int(sp["gezeigt"][0]), int(sp["gezeigt"][1])) + qa = LE.quantil(sv[st], w)[hk] + P.append((pid, st, int(code), zug, 0, float(qa), 1.0)) + elif sp["muck"] is not None and len(brett) == 5 and st == 3: + ev = ML.evidenz(brett, None, sp["muck"]) + wm = w * ev + if wm.sum() > 0: + qq = LE.quantil(sv[st], w) + idx = np.nonzero(wm)[0] + wmn = wm[idx] / wm.sum() + hist = np.bincount(np.minimum((qq[idx] * 10).astype(int), 9), weights=wmn, minlength=10) + for bi in range(10): + if hist[bi] > 0: + P.append((pid, st, int(code), zug, 1, (bi + 0.5) / 10, float(hist[bi]))) + return tag, D, P, C + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--tafel", required=True); ap.add_argument("--aus", required=True) + ap.add_argument("--jede", type=int, default=5); ap.add_argument("--prozesse", type=int, default=2) + ap.add_argument("--tage", type=int, default=0, help="only every k-th day (0 = all)") + a = ap.parse_args(argv) + if os.path.exists(a.aus): + sys.exit("exists, never overwritten: %s" % a.aus) + tage = sorted(f.split(".")[0] for f in os.listdir(os.path.join(PRUEF, "entscheidungen"))) + if a.tage: + tage = tage[::a.tage] + t0 = time.time() + import multiprocessing as mp + with mp.get_context("spawn").Pool(a.prozesse) as pool: + res = [] + for i, r in enumerate(pool.imap_unordered(tag_worker, [(t, a.tafel, a.jede, False) for t in tage])): + res.append(r); print("%d/%d %s %.0f s" % (i + 1, len(tage), r[0], time.time() - t0), flush=True) + D = [d for _, dd, _, _ in res for d in dd]; P = [p for _, _, pp, _ in res for p in pp]; C = [c for _, _, _, cc in res for c in cc] + tmp = a.aus + ".tmp" + os.makedirs(tmp) + cols = ("pid", "st", "code", "zug", "ll_tafel", "ll_freq", "ll_unif", "sh10", "sh50", "sh200", "aufg", "leer", "n_knoten", "floor", "ll_schrumpf", "ll_kal", "maske_aus") + np.savez(os.path.join(tmp, "entscheidungen.npz"), **{c: np.array([d[i] for d in D]) for i, c in enumerate(cols)}) + np.savez(os.path.join(tmp, "pit.npz"), **{c: np.array([p[i] for p in P]) for i, c in enumerate(("pid", "st", "code", "zug", "muck", "pit", "gewicht"))}) + np.savez(os.path.join(tmp, "bedingt.npz"), **{c: np.array([x[i] for x in C]) for i, c in enumerate(("pid", "st", "code", "zug", "ll_p", "ll_p_eps", "ll_kal", "ll_kal_eps", "ll_schr", "ll_schr_eps", "ll_freq", "ll_unif"))}) + json.dump({"tafel": a.tafel, "jede": a.jede, "tage": len(tage), "entscheidungen": len(D), "pit": len(P)}, open(os.path.join(tmp, "lauf.json"), "w")) + os.rename(tmp, a.aus) + print("done", len(D), len(P), "%.0f s" % (time.time() - t0)) + + +if __name__ == "__main__": + main() diff --git a/messung/motor/poolgegner_tafel/flop_rang.py b/messung/motor/poolgegner_tafel/flop_rang.py new file mode 100644 index 00000000..35114b48 --- /dev/null +++ b/messung/motor/poolgegner_tafel/flop_rang.py @@ -0,0 +1,69 @@ +# Flop strength axis: rank order of the 49 deterministic runouts (staerke_v5.brett_staerke_v5) against all 1176 runouts (turn < river pairs of the 49 free cards). +# Spearman per board over the live combos, and the effect on q (uniform range): mean / max |q49 - q1176| and the share of combos whose 20-bin index differs. +# python3 flop_rang.py --boards 30 --aus +# Boards are random flops (fixed seed), no real hands. +import sys, os; sys.dont_write_bytecode = True +import argparse, json, time +from itertools import combinations +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, HIER); sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import staerke as ST # noqa: E402 +import staerke_v5 as S5 # noqa: E402 +import lesen as LE # noqa: E402 + + +def voll(flop): + frei = [c for c in range(52) if c not in flop] + bretter = [list(flop) + list(p) for p in combinations(frei, 2)] + st, gueltig = ST._staerke_auslaeufe(bretter) + summe = np.zeros(1326) + for r in range(st.shape[0]): + summe += np.where(gueltig[r], st[r], 0.0) + zahl = gueltig.sum(0) + auf = (ST.KOMBI[:, :, None] == np.array(flop)[None, None, :]).any(-1).any(-1) + return np.where(auf | (zahl == 0), np.nan, summe / np.maximum(zahl, 1)) + + +def rang(x): + o = np.argsort(x, kind="stable"); r = np.empty(len(x)); r[o] = np.arange(len(x)) + # average ranks for ties + xs = x[o]; i = 0 + while i < len(xs): + j = i + while j + 1 < len(xs) and abs(xs[j + 1] - xs[i]) <= 1e-12: + j += 1 + r[o[i:j + 1]] = (i + j) / 2.0; i = j + 1 + return r + + +def main(argv=None): + ap = argparse.ArgumentParser(); ap.add_argument("--boards", type=int, default=30); ap.add_argument("--aus", required=True) + a = ap.parse_args(argv) + if os.path.exists(a.aus): + sys.exit("exists, never overwritten: %s" % a.aus) + rng = np.random.RandomState(1205) + out = []; t0 = time.time() + for _ in range(a.boards): + flop = sorted(rng.choice(52, 3, replace=False).tolist()) + s49 = S5.brett_staerke_v5(flop); s1176 = voll(flop) + ok = ~np.isnan(s49) & ~np.isnan(s1176) + r49, r1176 = rang(s49[ok]), rang(s1176[ok]) + sp = float(np.corrcoef(r49, r1176)[0, 1]) + w = ok.astype(float) + q49 = LE.quantil(s49, w)[ok]; q1176 = LE.quantil(s1176, w)[ok] + out.append({"flop": flop, "spearman": sp, "mean_abs_dq": float(np.abs(q49 - q1176).mean()), "max_abs_dq": float(np.abs(q49 - q1176).max()), + "anteil_bin_verschieden": float((LE.bin_von(q49) != LE.bin_von(q1176)).mean())}) + print("%d %.5f %.4f (%.0f s)" % (len(out), sp, out[-1]["mean_abs_dq"], time.time() - t0), flush=True) + sp = np.array([o["spearman"] for o in out]) + ges = {"boards": len(out), "spearman_mittel": float(sp.mean()), "spearman_min": float(sp.min()), "mean_abs_dq_mittel": float(np.mean([o["mean_abs_dq"] for o in out])), + "max_abs_dq": float(max(o["max_abs_dq"] for o in out)), "anteil_bin_verschieden_mittel": float(np.mean([o["anteil_bin_verschieden"] for o in out])), "je_board": out} + tmp = a.aus + ".tmp" + json.dump(ges, open(tmp, "w"), indent=1); os.rename(tmp, a.aus) + print({k: v for k, v in ges.items() if k != "je_board"}) + + +if __name__ == "__main__": + main() diff --git a/messung/motor/poolgegner_tafel/kern.py b/messung/motor/poolgegner_tafel/kern.py new file mode 100644 index 00000000..d3bb0789 --- /dev/null +++ b/messung/motor/poolgegner_tafel/kern.py @@ -0,0 +1,340 @@ +# Pool opponent table: the pure core. Turns the welt_v5 model (messlatte.V5Modell) plus aggregated E-step sums into table cells. No I/O here. +# Spec: tests/poolgegner_tafel_spec.py. Format: /Volumes/Alpha SSD/pokerfreak-daten/pruefstand/poolgegner-tafel/FORMAT.md. +# cell(node, q bin) P(a) = sum over variants v (type, legal mask, o) of mass_v * softmax_legal( u_type(node, q_bin) + o_v ) / sum mass +# u = alpha(level fallback) + o + lambda log2(bb/0.02) + beta[street] . hat(q) (+ gamma[class] preflop) -- exactly V5Modell.nutzen +import sys, os; sys.dont_write_bytecode = True +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "live")); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import knoten as KN # noqa: E402 +import messlatte as ML # noqa: E402 +import gamma as GA # noqa: E402 +from antworttafel_v3 import kappa as _kappa_momente # noqa: E402 (reused, not copied) + +BINS = 20 +NA = 6 +POOL_TYP = -1 # pseudo type: unknown player, alpha = pool-coarse only +VORFLOP_MAX = KN.VORFLOP_MAX +TOP_VARIANTEN = 16 +STUFEN_NAMEN = ("fein", "mittel", "grob", "pool", "keine") + + +def bin_mitten(): + return (np.arange(BINS) + 0.5) / BINS + + +def alle_codes_vorflop(): + return [c for c in range(VORFLOP_MAX) if _vorflop_gueltig(c)] + + +def _vorflop_gueltig(c): + t = KN.teile(c) + return t["pos"] < 6 and t["lage"] < 5 and t["eigen"] < 3 and t["steal"] < 2 and t["fach"] < 5 and ((((t["pos"] * 5 + t["lage"]) * 3 + t["eigen"]) * 2 + t["steal"]) * 5 + t["fach"]) == c + + +def alle_codes_nachflop(): + return list(range(VORFLOP_MAX, VORFLOP_MAX + 3 * 648)) + + +def strasse_von(code): + return 0 if code < VORFLOP_MAX else 1 + (code - VORFLOP_MAX) // 648 + + +# ---------- model access +def alpha_stufe(modell, t, codes): + """(alpha [6], level): 0 fine, 1 medium, 2 coarse (type table), 3 pool-coarse, 4 none (alpha = 0). Same fallback as V5Modell.alpha.""" + tafel = modell.tab.get(t) if t >= 0 else None + if tafel: + for lvl in (0, 1, 2): + v = tafel.get((lvl, int(codes[lvl]))) + if v is not None: + return v, lvl + pool = modell.tab.get(ML.POOL_KEY) + if pool: + v = pool.get((2, int(codes[2]))) + if v is not None: + return v, 3 + return np.zeros(NA), 4 + + +def codes_von(c): + return [int(c), KN.hoch(c, 1), KN.hoch(c, 2)] + + +def standard_variante(code): + """No data at the node: unknown player, all classes legal except fold where no bet is faced, o = 0.""" + erl = [1] * NA + if code >= VORFLOP_MAX and KN.teile(code)["gegen"] == 0: + erl[0] = 0 + return {"typ": POOL_TYP, "erl": erl, "o": [0.0] * NA, "masse": 1.0} + + +def varianten_zusammen(varianten, top_k=TOP_VARIANTEN, o_stellen=3): + """Merge equal (type, mask, o rounded) variants, keep the top_k by mass.""" + d = {} + for v in varianten: + k = (int(v["typ"]), tuple(int(x) for x in v["erl"]), tuple(round(float(x), o_stellen) for x in v["o"])) + if k in d: + d[k]["masse"] += float(v["masse"]) + else: + d[k] = {"typ": k[0], "erl": list(k[1]), "o": [float(x) for x in v["o"]], "masse": float(v["masse"])} + return sorted(d.values(), key=lambda x: -x["masse"])[:top_k] + + +def _gegen_zellen(code): + """List of delta cells (street, band, position) the node's decision faces when the HERO bet (gegenuns.zelle), or [] if the node never faces a hero bet. + Post-flop node `gegen` 1 (bet < 0.45 pot) mixes bands 0 and 1 (<= 0.25 | <= 0.45), 2..4 map to bands 2..4, 5 (raise) = band 5; node ip = 1 (actor in position) + means the hero acts before the opponent = delta position 0. Preflop: lage 2 = band fach, lage 3/4 = band 5, position unknown = both.""" + t = KN.teile(code) + if t["vorflop"]: + if t["lage"] == 2: + return [(0, t["fach"], 0), (0, t["fach"], 1)] + if t["lage"] >= 3: + return [(0, 5, 0), (0, 5, 1)] + return [] + g = t["gegen"] + if g == 0: + return [] + bands = (0, 1) if g == 1 else (g,) + pos = 0 if t["ip"] else 1 + return [(1 + t["st"], b, pos) for b in bands] + + +def mischung_p(modell, st, codes, qs, varianten, bb, gegen=None, klassen=False): + """Mixture over the variants: -> (P [n, 6], mass per fallback level [5], type mass dict). qs: q per row (bin centres post-flop; preflop 1326 per-combo q, rows returned = first combo of each class).""" + tot = sum(v["masse"] for v in varianten) + P = None + stufe = np.zeros(5) + for v in varianten: + _, s = alpha_stufe(modell, v["typ"], codes) + u = modell.nutzen(st, codes, qs, v["o"], v["typ"], bb, gegen=gegen) + p = ML._softmax_zeile(u, v["erl"]) + P = v["masse"] * p if P is None else P + v["masse"] * p + stufe[s] += v["masse"] + return P / tot, stufe / tot + + +def _mehrheit(stufe_masse): + m = stufe_masse.max() + return int(max(i for i in range(5) if stufe_masse[i] >= m - 1e-12)) # ties -> coarser level + + +def _ref_variante(varianten): + """Most massive (mask, o) over types: -> (mask bits, o [6], type mass dict).""" + d = {} + for v in varianten: + k = (tuple(v["erl"]), tuple(round(x, 3) for x in v["o"])) + d[k] = d.get(k, 0.0) + v["masse"] + erl, o = max(d, key=d.get) + ref_o = next(v["o"] for v in varianten if tuple(v["erl"]) == erl and tuple(round(x, 3) for x in v["o"]) == o) + typ = {} + for v in varianten: + if tuple(v["erl"]) == erl and tuple(round(x, 3) for x in v["o"]) == o: + typ[v["typ"]] = typ.get(v["typ"], 0.0) + v["masse"] + return sum(1 << a for a in range(NA) if erl[a]), np.array(ref_o), typ + + +# ---------- kappa and shrinkage +def kappa_eb(p, n, k): + """Empirical-Bayes kappa of cells around the model: Beta-binomial moments (antworttafel_v3.kappa), one 'group' per (cell, action) with 0 < p < 1 and n >= 2. inf = no over-dispersion.""" + p = np.asarray(p, float).ravel(); n = np.asarray(n, float).ravel(); k = np.asarray(k, float).ravel() + gruppen = [(float(pi), [(float(ki), float(ni))]) for pi, ni, ki in zip(p, n, k) if 0 < pi < 1 and ni >= 2] + return float(_kappa_momente(gruppen)[0]) + + +def schrumpfe(p, p_emp, n, kappa): + """(n p_emp + kappa p) / (n + kappa); equals p where n = 0, kappa = inf or no data (NaN).""" + p = np.asarray(p, float); p_emp = np.asarray(p_emp, float); n = np.asarray(n, float) + if kappa == float("inf"): + return p.copy() + n = n[..., None] if n.ndim == p.ndim - 1 else n + w = np.where((n > 0) & ~np.isnan(p_emp), n, 0.0) + return (w * np.nan_to_num(p_emp) + kappa * p) / (w + kappa) + + +def _kappa_tabelle(P, N, NAx, strasse, stufe): + """kappa per (street, level) group over all cells. P, NAx: [1, nodes, bins, 6]; N: [1, nodes, bins]; strasse, stufe: [1, nodes].""" + out = {} + for s in sorted(set(strasse.ravel().tolist())): + for lv in range(5): + m = (strasse == s) & (stufe == lv) + if not m.any(): + continue + p = P[m].reshape(-1, NA); n = np.repeat(N[m].reshape(-1), 1); k = NAx[m].reshape(-1, NA) + nn = N[m].reshape(-1) + sel = nn >= 2 + kap = kappa_eb(np.repeat(p[sel], 1, 0), np.repeat(nn[sel][:, None], NA, 1), k[sel]) + out["%d:%d" % (s, lv)] = {"kappa": kap, "zellen": int(sel.sum())} + return out + + +def _kappa_je_knoten(tab, strasse, stufe): + kn = np.full(strasse.shape, np.inf) + for key, v in tab.items(): + s, lv = (int(x) for x in key.split(":")) + kn[(strasse == s) & (stufe == lv)] = v["kappa"] + return kn + + +# ---------- build +def _aggregiere_ebene(code, p, n, na, aufg, lvl): + """Medium / coarse level: sums of n, na over the children; p = child mass-weighted mean of the children's p (equal weights if no data).""" + schl = np.array([KN.hoch(int(c), lvl) for c in code]) + codes = np.array(sorted(set(schl.tolist()))) + N = np.zeros((p.shape[0], len(codes), BINS)); NAx = np.zeros((p.shape[0], len(codes), BINS, NA)); P = np.zeros((p.shape[0], len(codes), BINS, NA)); A = np.zeros((p.shape[0], len(codes)), bool) + for j, c in enumerate(codes): + kin = np.where(schl == c)[0] + w = n[0, kin].sum(-1) + w = w / w.sum() if w.sum() > 0 else np.full(len(kin), 1.0 / len(kin)) + P[:, j] = np.einsum("k,lkbi->lbi", w, p[:, kin]); N[:, j] = n[:, kin].sum(1); NAx[:, j] = na[:, kin].sum(1); A[:, j] = aufg[:, kin].all(1) + with np.errstate(invalid="ignore", divide="ignore"): + pe = np.where(N[..., None] > 0, NAx / np.maximum(N[..., None], 1e-300), np.nan) + return {"code": codes, "p": P, "n": N, "na": NAx, "p_emp": pe, "aufgefuellt": A} + + +def _gegen_p(modell, st, codes, qs, var, bb, zellen): + ps = [mischung_p(modell, st, codes, qs, var, bb, gegen=z)[0] for z in zellen] + return np.mean(ps, axis=0) + + +def bauen_nachflop(modell, daten, bb, codes=None, mit_gegenuns=False, top_k=TOP_VARIANTEN): + """daten: {code: {"varianten": [{typ, erl, o, masse}], "na": [20, 6] posterior-weighted counts by bin and observed action}}. -> dict of arrays (axis 0 = limit, length 1).""" + codes = list(codes) if codes is not None else alle_codes_nachflop() + N_ = len(codes); qs = bin_mitten() + out = {k: np.zeros(s) for k, s in (("p", (1, N_, BINS, NA)), ("p_ref", (1, N_, BINS, NA)), ("o_ref", (1, N_, NA)), ("n", (1, N_, BINS)), ("na", (1, N_, BINS, NA)), ("anteil_fein", (1, N_)))} + out["mask_ref"] = np.zeros((1, N_), np.uint8); out["stufe"] = np.zeros((1, N_), np.uint8) + out["aufgefuellt"] = np.zeros((1, N_), bool); out["aufgefuellt_leer"] = np.zeros((1, N_), bool); out["gegen_gilt"] = np.zeros((1, N_), bool) + out["p_gegenuns"] = np.zeros((1, N_, BINS, NA)); out["code"] = np.array(codes, np.int32); out["strasse"] = np.array([[strasse_von(c) for c in codes]], np.int8) + for i, c in enumerate(codes): + d = daten.get(c) + var = varianten_zusammen(d["varianten"], top_k) if d and d["varianten"] else [standard_variante(c)] + cd = codes_von(c); st = strasse_von(c) + P, stufe = mischung_p(modell, st, cd, qs, var, bb) + bits, o_ref, typ = _ref_variante(var) + erl = [(bits >> a) & 1 for a in range(NA)] + pref, _ = mischung_p(modell, st, cd, qs, [{"typ": t, "erl": erl, "o": o_ref, "masse": m} for t, m in typ.items()], bb) + out["p"][0, i] = P; out["p_ref"][0, i] = pref; out["o_ref"][0, i] = o_ref; out["mask_ref"][0, i] = bits + out["stufe"][0, i] = _mehrheit(stufe); out["anteil_fein"][0, i] = stufe[0] + na = np.asarray(d["na"], float) if d else np.zeros((BINS, NA)) + out["na"][0, i] = na; out["n"][0, i] = na.sum(-1) + out["aufgefuellt"][0, i] = stufe[0] == 0.0 + out["aufgefuellt_leer"][0, i] = bool(stufe[4] > 0.5) + gz = _gegen_zellen(c) if mit_gegenuns and modell.gegen is not None else [] + out["gegen_gilt"][0, i] = bool(gz) + out["p_gegenuns"][0, i] = _gegen_p(modell, st, cd, qs, var, bb, gz) if gz else P + with np.errstate(invalid="ignore", divide="ignore"): + out["p_emp"] = np.where(out["n"][..., None] > 0, out["na"] / np.maximum(out["n"][..., None], 1e-300), np.nan) + out["n_knoten"] = out["n"].sum(-1) + tab = _kappa_tabelle(out["p"], out["n"], out["na"], out["strasse"], out["stufe"]) + out["kappa_tabelle"] = tab + out["kappa"] = _kappa_je_knoten(tab, out["strasse"], out["stufe"]) + out["p_schrumpf"] = np.stack([schrumpfe(out["p"][0, i], out["p_emp"][0, i], out["n"][0, i], float(out["kappa"][0, i])) for i in range(N_)])[None] + out["kappa_marginal"] = {"%d" % k: {"kappa": v} for k, v in kappa_marginal(out["p"], out["n"], out["na"], out["strasse"]).items()} + out["p_kal"], out["kal_delta"] = kalibriere(out["p"], out["n"], out["na"], {int(k): v["kappa"] for k, v in out["kappa_marginal"].items()}, out["strasse"]) + out["l1"] = _aggregiere_ebene(out["code"], out["p"], out["n"], out["na"], out["aufgefuellt"], 1) + out["l2"] = _aggregiere_ebene(out["code"], out["p"], out["n"], out["na"], out["aufgefuellt"], 2) + out["limit_bb"] = np.array([bb]) + return out + + +def klassen_rep(): + """Index of the first combo of each of the 169 classes.""" + return np.array([int(np.argmax(GA.KLASSE_VON_KOMBI == k)) for k in range(GA.NK)]) + + +def klasse_q0(modell): + """Static q of each class in the full range (all combos weight 1).""" + s = modell.staerke(0, []) + return ML.quantil(s, np.ones(1326))[klassen_rep()] + + +def bauen_vorflop(modell, daten, bb, codes=None, mit_gegenuns=False, top_k=TOP_VARIANTEN): + """daten: {code: {"varianten": [...], "na": [169, 6], "qbar": [169] (NaN = none)}}. Preflop cells: node x 169 classes, q = data-weighted mean q of the class at the node + (static q of the class where no data). The class effect gamma of the model is inside nutzen.""" + codes = list(codes) if codes is not None else alle_codes_vorflop() + N_ = len(codes); K = GA.NK; rep = klassen_rep(); q0 = klasse_q0(modell) + out = {k: np.zeros(s) for k, s in (("p", (1, N_, K, NA)), ("p_ref", (1, N_, K, NA)), ("o_ref", (1, N_, NA)), ("n", (1, N_, K)), ("na", (1, N_, K, NA)), ("qbar", (1, N_, K)), ("anteil_fein", (1, N_)))} + out["mask_ref"] = np.zeros((1, N_), np.uint8); out["stufe"] = np.zeros((1, N_), np.uint8) + out["aufgefuellt"] = np.zeros((1, N_), bool); out["aufgefuellt_leer"] = np.zeros((1, N_), bool); out["gegen_gilt"] = np.zeros((1, N_), bool) + out["p_gegenuns"] = np.zeros((1, N_, K, NA)); out["code"] = np.array(codes, np.int32); out["strasse"] = np.zeros((1, N_), np.int8) + for i, c in enumerate(codes): + d = daten.get(c) + var = varianten_zusammen(d["varianten"], top_k) if d and d["varianten"] else [standard_variante(c)] + cd = codes_von(c) + qb = np.asarray(d["qbar"], float) if d else np.full(K, np.nan) + qk = np.where(np.isnan(qb), q0, qb) + q1326 = qk[GA.KLASSE_VON_KOMBI] + P, stufe = mischung_p(modell, 0, cd, q1326, var, bb) + bits, o_ref, typ = _ref_variante(var) + erl = [(bits >> a) & 1 for a in range(NA)] + pref, _ = mischung_p(modell, 0, cd, q1326, [{"typ": t, "erl": erl, "o": o_ref, "masse": m} for t, m in typ.items()], bb) + out["p"][0, i] = P[rep]; out["p_ref"][0, i] = pref[rep]; out["o_ref"][0, i] = o_ref; out["mask_ref"][0, i] = bits; out["qbar"][0, i] = qk + out["stufe"][0, i] = _mehrheit(stufe); out["anteil_fein"][0, i] = stufe[0] + na = np.asarray(d["na"], float) if d else np.zeros((K, NA)) + out["na"][0, i] = na; out["n"][0, i] = na.sum(-1) + out["aufgefuellt"][0, i] = stufe[0] == 0.0 + out["aufgefuellt_leer"][0, i] = bool(stufe[4] > 0.5) + gz = _gegen_zellen(c) if mit_gegenuns and modell.gegen is not None else [] + out["gegen_gilt"][0, i] = bool(gz) + out["p_gegenuns"][0, i] = (np.mean([mischung_p(modell, 0, cd, q1326, var, bb, gegen=z)[0] for z in gz], axis=0)[rep]) if gz else P[rep] + with np.errstate(invalid="ignore", divide="ignore"): + out["p_emp"] = np.where(out["n"][..., None] > 0, out["na"] / np.maximum(out["n"][..., None], 1e-300), np.nan) + out["n_knoten"] = out["n"].sum(-1) + tab = _kappa_tabelle(out["p"], out["n"], out["na"], out["strasse"], out["stufe"]) + out["kappa_tabelle"] = tab + out["kappa"] = _kappa_je_knoten(tab, out["strasse"], out["stufe"]) + out["p_schrumpf"] = np.stack([schrumpfe(out["p"][0, i], out["p_emp"][0, i], out["n"][0, i], float(out["kappa"][0, i])) for i in range(N_)])[None] + out["kappa_marginal"] = {"%d" % k: {"kappa": v} for k, v in kappa_marginal(out["p"], out["n"], out["na"], out["strasse"]).items()} + out["p_kal"], out["kal_delta"] = kalibriere(out["p"], out["n"], out["na"], {int(k): v["kappa"] for k, v in out["kappa_marginal"].items()}, out["strasse"]) + out["limit_bb"] = np.array([bb]) + return out + + +# ---------- node-level marginal recalibration (p_kal) +KAL_ITER = 200 +KAL_TOL = 1e-10 + + +def kappa_marginal(p, n, na, strasse): + """kappa per street of the NODE marginals around the model: child = (observed count of action a at the node, node n), parent = model marginal under the data cell weights. + -> {street: kappa}. inf = the node marginals are binomial-consistent with the model.""" + out = {} + N = p.shape[1] + marg = np.zeros((N, NA)); nt = np.zeros(N); kt = np.zeros((N, NA)) + for i in range(N): + w = n[0, i] + if w.sum() > 0: + marg[i] = (w[:, None] * p[0, i]).sum(0) / w.sum() + nt[i] = w.sum(); kt[i] = na[0, i].sum(0) + for s in sorted(set(strasse.ravel().tolist())): + m = (strasse[0] == s) & (nt >= 2) + out[int(s)] = kappa_eb(marg[m], np.repeat(nt[m][:, None], NA, 1), kt[m]) if m.any() else float("inf") + return out + + +def kalibriere(p, n, na, kappa_je_strasse, strasse): + """p [1, N, C, 6], n [1, N, C], na [1, N, C, 6]. Per node, tilt the logits by delta [6] so that the data-weighted marginal sum_c n_c p_c(a) / sum n equals the target + (na_tot + kappa * marginal) / (n_tot + kappa) (kappa = inf or n = 0: unchanged). Zeros stay zeros. -> (p_kal, delta [1, N, 6]).""" + out = p.copy(); delta = np.zeros((1, p.shape[1], NA)) + for i in range(p.shape[1]): + w = n[0, i]; nt = w.sum() + kap = kappa_je_strasse.get(int(strasse[0, i]), float("inf")) + if nt <= 0 or kap == float("inf"): + continue + P = p[0, i] + marg = (w[:, None] * P).sum(0) / nt + tgt = (na[0, i].sum(0) + kap * marg) / (nt + kap) + akt = (marg > 0) & (tgt > 0) + d = np.zeros(NA) + for _ in range(KAL_ITER): + X = P * np.exp(d)[None, :] + X = X / X.sum(1, keepdims=True) + mg = (w[:, None] * X).sum(0) / nt + diff = np.log(np.where(akt, tgt, 1.0)) - np.log(np.where(akt, np.maximum(mg, 1e-300), 1.0)) + if np.abs(diff).max() < KAL_TOL: + break + d = d + diff + out[0, i] = X; delta[0, i] = d + return out, delta diff --git a/messung/motor/poolgegner_tafel/lesen.py b/messung/motor/poolgegner_tafel/lesen.py new file mode 100644 index 00000000..aa70673c --- /dev/null +++ b/messung/motor/poolgegner_tafel/lesen.py @@ -0,0 +1,83 @@ +# Pool opponent table: reference reader (pure numpy). `Tafel.lade(ordner)`, `Tafel.verteilung(...)` (post-flop: q from the forward range, bin lookup, mask renormalisation), +# `Tafel.verteilung_vorflop(...)`, `fortschreiben` (forward range update), `quantil` (midpoint rule). Same code the spec and the held-out evaluation run. +# Format: FORMAT.md in the table folder. Spec: tests/poolgegner_tafel_spec.py. +import sys; sys.dont_write_bytecode = True +import json, os +import numpy as np + +BINS = 20 +TOL = 1e-12 + + +def quantil(staerke, gewicht): + """Midpoint rule: q = (mass below h + mass of h / 2) / total mass; equal strength (|d| <= TOL) shares the group midpoint; NaN strength has mass 0; total 0 -> q = 0.5.""" + s = np.asarray(staerke, dtype=float); w = np.where(np.isnan(s), 0.0, np.asarray(gewicht, dtype=float)) + s = np.where(np.isnan(s), -1.0, s) + ordn = np.argsort(s, kind="stable"); ss = s[ordn] + kum = np.concatenate([[0.0], np.cumsum(w[ordn])]) + gesamt = kum[-1] + if not gesamt > 0: + return np.full(len(s), 0.5) + lo = np.searchsorted(ss, s - TOL, "left"); hi = np.searchsorted(ss, s + TOL, "right") + return (kum[lo] + 0.5 * (kum[hi] - kum[lo])) / gesamt + + +def bin_von(q): + return np.minimum(np.maximum((np.asarray(q) * BINS).astype(np.int64), 0), BINS - 1) + + +def fortschreiben(w, P, zug): + """Forward range after the observed class `zug`: w * P[:, zug]; if the mass would become 0 the old range is kept (Welt5 `rueckfall`).""" + neu = w * P[:, zug] + return neu if neu.sum() > 0 else w + + +def _maske_normieren(P, erlaubt, zaehler): + m = np.asarray(erlaubt, float) + X = P * m + s = X.sum(-1, keepdims=True) + leer = (s <= 1e-12).ravel() + if leer.any(): # legal mask outside the cell's typical mask: uniform over legal (counted) + zaehler["maske_ausserhalb"] += int(leer.sum()) + X[leer] = m + s = X.sum(-1, keepdims=True) + return X / s + + +class Tafel: + def __init__(self, ordner, meta, teile): + self.ordner, self.meta = ordner, meta + self.nachflop = teile.get("nachflop"); self.vorflop = teile.get("vorflop") + self.zaehler = {"maske_ausserhalb": 0, "aufgefuellt_abfragen": 0} + self._idx = {n: {int(c): i for i, c in enumerate(t["code"])} for n, t in teile.items()} + + @classmethod + def lade(cls, ordner, mmap=True): + with open(os.path.join(ordner, "meta.json")) as f: + meta = json.load(f) + teile = {} + for name in meta["teile"]: + with open(os.path.join(ordner, name + ".kopf.json")) as f: + kopf = json.load(f) + pfad = os.path.join(ordner, name + ".bin") + teile[name] = {k["name"]: (np.memmap(pfad, dtype=np.dtype(k["dtype"]), mode="r", offset=k["offset"], shape=tuple(k["shape"])) if mmap else + np.fromfile(pfad, dtype=np.dtype(k["dtype"]), count=int(np.prod(k["shape"])), offset=k["offset"]).reshape(k["shape"])) + for k in kopf["arrays"]} + return cls(ordner, meta, teile) + + def verteilung(self, code, w, staerke, erlaubt, variante="p", limit=0): + """Post-flop decision: forward range w [1326] and strength [1326] -> (P [1326, 6] over the legal classes, q [1326]). variante: "p" | "p_gegenuns" | "p_schrumpf".""" + t = self.nachflop; i = self._idx["nachflop"][int(code)] + q = quantil(staerke, w) + b = bin_von(q) + if bool(t["aufgefuellt"][limit, i]): + self.zaehler["aufgefuellt_abfragen"] += 1 + return _maske_normieren(np.asarray(t[variante][limit, i])[b].astype(float), erlaubt, self.zaehler), q + + def verteilung_vorflop(self, code, klasse_von_kombi, erlaubt, variante="p", limit=0): + """Preflop decision: row per class (q baked in) -> (P [1326, 6], qbar of the class per combo).""" + t = self.vorflop; i = self._idx["vorflop"][int(code)] + if bool(t["aufgefuellt"][limit, i]): + self.zaehler["aufgefuellt_abfragen"] += 1 + P = np.asarray(t[variante][limit, i])[klasse_von_kombi].astype(float) + return _maske_normieren(P, erlaubt, self.zaehler), np.asarray(t["qbar"][limit, i])[klasse_von_kombi] diff --git a/messung/motor/poolgegner_tafel/modellwahl.py b/messung/motor/poolgegner_tafel/modellwahl.py new file mode 100644 index 00000000..6ba41c89 --- /dev/null +++ b/messung/motor/poolgegner_tafel/modellwahl.py @@ -0,0 +1,88 @@ +# "Which model wins where": per node class (river, bet faced band k/m/g/u x opponent in position or not) the log loss per decision of the candidates on the SAME held-out rows +# (days 308-385, response to a river bet, heads up, no all-in): pool table v5.1 (p, p_kal) and the Temperatur response curve (raw cell rate, Laplace 0.5). Winner per class by the paired +# difference with a 95 % bootstrap over responders (interval excludes 0 -> winner, else "unentschieden"); anything not decided by this card is "ungeprueft". +# Live cross-check in the same run: fold rate of each candidate (same rows) against the live fold rate against OUR river bets (answer table, Wilson 95 %); a candidate outside the +# live interval in a class is marked "bekannt falsch" (consumer reads p = 0 there). +# python3 modellwahl.py +import sys, os; sys.dont_write_bytecode = True +import json +import numpy as np + +B = 2000 +FLOOR = 1e-4 +BANDNAMEN = {1: "vs-klein (<0,45)", 2: "vs-mittel (0,45-0,85)", 3: "vs-gross (0,85-1,2)", 4: "vs-over (>1,2)"} +BIS = {1: 0.45, 2: 0.85, 3: 1.3, 4: 99.0} + + +def ll(p, obs): + return -np.log(np.maximum(p[np.arange(len(obs)), obs], FLOOR)) + + +def boot(gid, vals, rng): + """mean and 95 % interval of vals [n, k] with resampling of responders (gid).""" + _, gi = np.unique(gid, return_inverse=True); G = gi.max() + 1 + n_g = np.bincount(gi, minlength=G).astype(float) + s_g = np.stack([np.bincount(gi, weights=vals[:, j], minlength=G) for j in range(vals.shape[1])], 1) + pt = s_g.sum(0) / n_g.sum() + est = np.empty((B, vals.shape[1])) + for b0 in range(0, B, 200): + W = rng.multinomial(G, np.full(G, 1.0 / G), size=min(200, B - b0)).astype(float) + est[b0:b0 + 200] = (W @ s_g) / (W @ n_g)[:, None] + return pt, np.percentile(est, 2.5, axis=0), np.percentile(est, 97.5, axis=0) + + +def main(argv): + vg, tafel, aus = argv[1:4] + if os.path.exists(aus): + sys.exit("exists, never overwritten: %s" % aus) + z = dict(np.load(os.path.join(vg, "zeilen.npz"))) + meta = json.load(open(os.path.join(tafel, "meta.json"))) + live = {(r["strasse"], r["bis"], r["position_wir"]): r for r in meta["gegenuns_live"]} + obs = z["obs"] + L = {"v5.1 p": ll(z["pv5"], obs), "v5.1 p_kal": ll(z["pkal"], obs), "Temperatur-Kurve": ll(z["ptemp"], obs)} + names = list(L) + rng = np.random.RandomState(1205) + rows = [] + sel_list = [("alle", np.ones(len(obs), bool))] + [("%s | %s" % (BANDNAMEN[g], "Gegner in Position" if ip else "Gegner ohne Position"), (z["gegen"] == g) & (z["ip"] == ip)) for g in (1, 2, 3, 4) for ip in (0, 1)] + for name, m in sel_list: + if m.sum() < 50: + continue + V = np.stack([L[k][m] for k in names], 1) + pt, lo, hi = boot(z["gid"][m], V, rng) + best = int(np.argmin(pt)) + diffs = [] + for j in range(len(names)): + if j == best: + continue + d = V[:, j] - V[:, best] + dp, dl, dh = boot(z["gid"][m], d[:, None], rng) + diffs.append((names[j], float(dp[0]), float(dl[0]), float(dh[0]))) + klar = all(x[2] > 0 for x in diffs) + # live cross-check (river only): model fold vs live fold against OUR bets + g = int(np.bincount(z["gegen"][m]).argmax()) if name != "alle" else None + lv = None + if g is not None: + ipv = int(z["ip"][m][0]) + lv = live.get((3, BIS[g], "oop" if ipv else "ip")) + fold = {k: float(p[m][:, 0].mean()) for k, p in (("v5.1 p", z["pv5"]), ("v5.1 p_kal", z["pkal"]), ("Temperatur-Kurve", z["ptemp"]))} + check = None + if lv: + check = {"live_fold": lv["live_k"] / lv["live_n"], "lo": lv["lo"], "hi": lv["hi"], "n": lv["live_n"], + "kandidat_fold": fold, "bekannt_falsch": [k for k, v in fold.items() if not (lv["lo"] <= v <= lv["hi"])]} + rows.append({"klasse": name, "n": int(m.sum()), "spieler": int(len(np.unique(z["gid"][m]))), "ll": {k: [float(pt[i]), float(lo[i]), float(hi[i])] for i, k in enumerate(names)}, + "gewinner": names[best] if klar else "unentschieden (bester: %s)" % names[best], "abstand_zum_besten": diffs, "live_check": check, + "status": "gemessen (Richter: zurueckgehaltene Tage 308-385)" if klar else "ungeprueft (kein klarer Sieger)"}) + tmp = aus + ".tmp"; os.makedirs(tmp) + json.dump({"hinweis": "log loss nats per decision, lower = better; paired difference to the best model with 95 % bootstrap over responders", "zeilen": rows}, open(os.path.join(tmp, "modellwahl.json"), "w"), indent=1) + md = ["| node class | n | " + " | ".join(names) + " | winner | live check (river, our bets) |", "|---|---|" + "---|" * len(names) + "---|---|"] + for r in rows: + c = r["live_check"] + lc = "-" if not c else "live %.1f%% [%.1f; %.1f] n %d; wrong: %s" % (100 * c["live_fold"], 100 * c["lo"], 100 * c["hi"], c["n"], ", ".join(c["bekannt_falsch"]) or "none") + md.append("| %s | %d | " % (r["klasse"], r["n"]) + " | ".join("%.4f [%.4f; %.4f]" % tuple(r["ll"][k]) for k in names) + " | %s | %s |" % (r["gewinner"], lc)) + open(os.path.join(tmp, "modellwahl.md"), "w").write("\n".join(md) + "\n") + os.rename(tmp, aus) + print("\n".join(md)) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/messung/motor/poolgegner_tafel/schreiben.py b/messung/motor/poolgegner_tafel/schreiben.py new file mode 100644 index 00000000..acc6fe4a --- /dev/null +++ b/messung/motor/poolgegner_tafel/schreiben.py @@ -0,0 +1,90 @@ +# Pool opponent table: writer. Atomic (temp folder, then rename), never overwrites, writes npz (Python) and flat little-endian binary + JSON header (mmap, no numpy), +# SHA256SUMS. Spec: tests/poolgegner_tafel_spec.py. +import sys; sys.dont_write_bytecode = True +import hashlib, json, os, shutil +import numpy as np + +FLOAT = np.dtype(" 4: + return a.astype(".npz, .bin + .kopf.json, meta.json, SHA256SUMS. dateien: extra files (paths) copied in. + Raises FileExistsError if the target exists (never overwritten).""" + if os.path.exists(ordner): + raise FileExistsError("never overwritten: %s" % ordner) + tmp = "%s.tmp%d" % (ordner, os.getpid()) + os.makedirs(tmp) + try: + meta = dict(meta); meta["teile"] = {} + for name, d in teile.items(): + arrs, rest = _flach(d) + np.savez(os.path.join(tmp, name + ".npz"), **arrs) + kopf = []; off = 0 + with open(os.path.join(tmp, name + ".bin"), "wb") as f: + for k, a in arrs.items(): + a = np.ascontiguousarray(a) + if a.dtype.byteorder == ">": + a = a.astype(a.dtype.newbyteorder("<")) + kopf.append({"name": k, "dtype": a.dtype.str, "shape": list(a.shape), "offset": off}) + f.write(a.tobytes()); off += a.nbytes + with open(os.path.join(tmp, name + ".kopf.json"), "w") as f: + json.dump({"arrays": kopf, "bytes": off}, f, indent=1) + meta["teile"][name] = {"arrays": [k["name"] for k in kopf]} + for k, v in rest.items(): + meta.setdefault("zusatz", {}).setdefault(name, {})[k] = v + with open(os.path.join(tmp, "meta.json"), "w") as f: + json.dump(meta, f, indent=1, default=_json) + for p in dateien: + shutil.copy(p, os.path.join(tmp, os.path.basename(p))) + with open(os.path.join(tmp, "SHA256SUMS"), "w") as f: + for n in sorted(os.listdir(tmp)): + if n != "SHA256SUMS": + f.write("%s %s\n" % (_sha(os.path.join(tmp, n)), n)) + if os.path.exists(ordner): + raise FileExistsError("never overwritten: %s" % ordner) + os.rename(tmp, ordner) + except BaseException: + shutil.rmtree(tmp, ignore_errors=True) + raise diff --git a/messung/motor/poolgegner_tafel/vektoren.py b/messung/motor/poolgegner_tafel/vektoren.py new file mode 100644 index 00000000..0da5113c --- /dev/null +++ b/messung/motor/poolgegner_tafel/vektoren.py @@ -0,0 +1,86 @@ +# Pool opponent table: test vectors for the trainer's Rust reader. Each vector = one decision of a held-out hand (public history only, no ids): the fine node code (knoten.Lauf.knoten), +# legal mask, forward range w[1326] before the decision, strength s[1326], q[1326], bin[1326], P[1326, 6] (table row, mask renormalised), observed class. Reader = lesen.Tafel. +# Files (SSD only, hands never in Git): /testvektoren.json (index, history, scalar fields) + testvektoren.npz (float64 arrays w, s, q, P; int arrays bin). +# python3 vektoren.py --tafel
--aus [--n 400] +import sys, os; sys.dont_write_bytecode = True +import argparse, gzip, json +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, HIER); sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import lesen as LE # noqa: E402 +import messlatte as ML # noqa: E402 +import staerke as ST # noqa: E402 +import gamma as GA # noqa: E402 +import knoten as KN # noqa: E402 +import vorverarbeitung as VP # noqa: E402 +import welt_v4 as W4 # noqa: E402 + +PRUEF = "/Volumes/Alpha SSD/pokerfreak-daten/welt_v5/pruef" +PARAMETER = os.path.join(V5, "parameter", "v5.1-gegenuns.json") +WELT = os.path.join(V5, "..", "welt_v4", "welt_v4.json.gz") +ZIEL = {0: 0.40, 1: 0.25, 2: 0.20, 3: 0.15} # share of vectors per street + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--tafel", required=True); ap.add_argument("--aus", required=True); ap.add_argument("--n", type=int, default=400) + a = ap.parse_args(argv) + if os.path.exists(a.aus): + sys.exit("exists, never overwritten: %s" % a.aus) + tafel = LE.Tafel.lade(a.tafel, mmap=False) + with open(PARAMETER, encoding="utf-8") as f: + par = json.load(f) + modell = ML.V5Modell(par, ST.vorflop_staerke(par["vorflop"])) + welt = W4.Welt(WELT) + want = {s: int(round(a.n * x)) for s, x in ZIEL.items()} + have = {s: 0 for s in want} + vek = []; arr = {} + tage = sorted(f.split(".")[0] for f in os.listdir(os.path.join(PRUEF, "roh"))) + for tag in tage[::7]: + if all(have[s] >= want[s] for s in want): + break + with gzip.open(os.path.join(PRUEF, "roh", tag + ".jsonl.gz"), "rt") as f: + hands = [json.loads(z) for z in f] + for h in hands[::9]: + if all(have[s] >= want[s] for s in want): + break + z = VP.zeile(h, welt, bb=0.02, tag=tag) + if z is None: + continue + brett = z["brett"]; live = ML.lebende(brett, []).astype(float); sv = {} + for sp in z["spieler"]: + if not sp["ents"]: + continue + w = live.copy() + for di, e in enumerate(sp["ents"]): + st = e["st"]; code = e["codes"][0] + if st not in sv: + sv[st] = modell.staerke(st, brett) + try: + if st == 0: + Pm, q = tafel.verteilung_vorflop(code, GA.KLASSE_VON_KOMBI, e["erlaubt"]) + else: + Pm, q = tafel.verteilung(code, w, sv[st], e["erlaubt"]) + except KeyError: + continue + if have[st] < want[st] and (len(vek) % 2 == 0 or st > 0): + i = len(vek) + vek.append({"i": i, "strasse": st, "brett": [int(c) for c in brett[:(0, 3, 4, 5)[st]]], "code": [int(c) for c in e["codes"]], "erlaubt": e["erlaubt"], "zug": int(e["zug"]), + "platz": sp["platz"], "spieler_n": len(h["s"]), "handsatz": {"s": [{"st": x.get("st")} for x in h["s"]], "bl": h.get("bl"), "an": h.get("an"), "z": h["z"]}}) + for k, v in (("w", w), ("s", sv[st]), ("q", q), ("P", Pm)): + arr.setdefault(k, []).append(np.asarray(v, float)) + arr.setdefault("bin", []).append(LE.bin_von(q) if st > 0 else np.zeros(1326, int)) + have[st] += 1 + w = LE.fortschreiben(w, Pm, e["zug"]) + tmp = a.aus + ".tmp"; os.makedirs(tmp) + json.dump({"hinweis": "decision index within the player's decisions of the hand = position of the vector's decision among that seat's entries; the history 'handsatz' is Handsatz v1 without ids; platz = seat index (start order from SB)", + "bins": LE.BINS, "vektoren": vek}, open(os.path.join(tmp, "testvektoren.json"), "w")) + np.savez(os.path.join(tmp, "testvektoren.npz"), **{k: np.stack(v) for k, v in arr.items()}) + os.rename(tmp, a.aus) + print("vectors", len(vek), have) + + +if __name__ == "__main__": + main() diff --git a/messung/motor/poolgegner_tafel/vergleich_temperatur.py b/messung/motor/poolgegner_tafel/vergleich_temperatur.py new file mode 100644 index 00000000..7b8ed846 --- /dev/null +++ b/messung/motor/poolgegner_tafel/vergleich_temperatur.py @@ -0,0 +1,173 @@ +# Which model wins where: the pool table (Welt v5.1, read through lesen.Tafel) against the measured response curve of the session "Gegner-Temperatur" +# (raw cell rates of learn days 0-307 with Laplace 0.5, fallback L0 -> L3 by n_min_zelle) on the SAME rows: opponent response (fold / call / raise) to a river BET (art bet, no all-in, heads up) +# on the held-out days 308-385 (26.08.-16.11.2026) of the day files in gedaechtnis2/hhd. Rows and cell keys come from their extract river_hu.npz (read only); the v5 side re-plays +# the hand (vorverarbeitung.zeile) and predicts the responder's river decision with the forward range (marginal over his hand). Log loss per decision in nats (lower = better), 95 % bootstrap over responders. +# python3 vergleich_temperatur.py --tafel
--aus [--jede 12] [--prozesse 2] +import sys, os; sys.dont_write_bytecode = True +import argparse, gzip, json, time +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "..", "batterie", "v2", "welt_v5") +sys.path.insert(0, HIER); sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import lesen as LE # noqa: E402 +import messlatte as ML # noqa: E402 +import staerke as ST # noqa: E402 +import knoten as KN # noqa: E402 +import vorverarbeitung as VP # noqa: E402 +import welt_v4 as W4 # noqa: E402 +import gamma as GA # noqa: E402 + +SSD = "/Volumes/Alpha SSD/pokerfreak-daten" +HHD = SSD + "/gedaechtnis2/hhd" +NPZ = SSD + "/pruefstand/temperatur-technik-rein/dosis2/spiegel-work/river_hu.npz" +KURVE = SSD + "/temperatur/antwortkurve-0512/antwortkurve.json" +PARAMETER = os.path.join(V5, "parameter", "v5.1-gegenuns.json") +WELT = os.path.join(V5, "..", "welt_v4", "welt_v4.json.gz") +SCHNITT = 308 +FLOOR = 1e-4 +FELDER = {"L0": ("art", "ip", "rolle", "topf", "grob", "gegen", "eigen", "fach"), "L1": ("art", "ip", "rolle", "gegen", "fach"), "L2": ("art", "ip", "fach"), "L3": ("art", "fach")} +BAND = "kmgu" +VARIANTEN = ("p", "p_kal") + + +def zeilen(npz): + """A rows (their definition, antwort_tafel.laden): actor bets or raises; here only bets (art 0), no all-in fach.""" + g = np.load(npz, allow_pickle=True) + ma = g["zug"] >= 3 + anteil, bis, pot, zahlen, hinten = (g[k][ma] for k in ("anteil", "bis", "pot", "zahlen", "hinten_a")) + hoch = bis - anteil * (pot + zahlen); stand = hoch - zahlen + band = (anteil + 1e-9 >= 0.45).astype(int) + (anteil + 1e-9 >= 0.85) + (anteil + 1e-9 >= 1.2) + fach = np.where(bis >= 0.97 * (stand + hinten), 4, band) + a = {"art": (g["zug"][ma] == 4).astype(np.int64), "fach": fach.astype(np.int64), "ant": g["antwort"][ma], "datei": g["datei"][ma], "hid": g["hid"][ma], "gid": g["gegner"][ma]} + for k in ("ip", "rolle", "topf", "grob", "gegen", "eigen"): + a[k] = g[k][ma] + return a + + +def schluessel(a, felder, m): + k = np.zeros(int(m.sum()), np.int64) + for f in felder: + k = k * 64 + a[f][m].astype(np.int64) + 1 + return k + + +def temperatur_vorhersage(a, n_min): + """Cell rates of the learn days (datei < 308) per level; for each test row the finest level with n >= n_min. -> p [rows, 3] for ant 1..3, level.""" + lern = (a["datei"] < SCHNITT) & (a["ant"] >= 1) & (a["ant"] <= 3) & (a["art"] == 0) & (a["fach"] < 4) + test = (a["datei"] >= SCHNITT) & (a["ant"] >= 1) & (a["ant"] <= 3) & (a["art"] == 0) & (a["fach"] < 4) + idx = np.nonzero(test)[0] + p = np.full((len(idx), 3), np.nan); stufe = np.full(len(idx), -1) + for li, lv in reversed(list(enumerate(("L0", "L1", "L2", "L3")))): + kl = schluessel(a, FELDER[lv], lern); kt = schluessel(a, FELDER[lv], test) + uk, inv = np.unique(kl, return_inverse=True) + cnt = np.stack([np.bincount(inv, weights=(a["ant"][lern] == c).astype(float), minlength=len(uk)) for c in (1, 2, 3)], 1) + pos = np.searchsorted(uk, kt); pos = np.minimum(pos, len(uk) - 1) + ok = uk[pos] == kt + n = cnt[pos].sum(1) + ok &= n >= n_min + pp = (cnt[pos] + 0.5) / (n[:, None] + 1.5) + p[ok] = pp[ok]; stufe[ok] = li + return idx, p, stufe + + +def v5_worker(args): + datei_name, hids, tafel_pfad = args + tafel = LE.Tafel.lade(tafel_pfad, mmap=False) + with open(PARAMETER, encoding="utf-8") as f: + par = json.load(f) + modell = ML.V5Modell(par, ST.vorflop_staerke(par["vorflop"])) + welt = W4.Welt(WELT) + tag = datei_name[:10] + out = [] + with gzip.open(os.path.join(HHD, datei_name), "rt") as f: + for z in f: + i0 = z.find('"h":"') + try: + hid = int(z[i0 + 5:z.find('"', i0 + 5)]) + except ValueError: + continue + if hid not in hids: + continue + hh = json.loads(z) + row = VP.zeile(hh, welt, bb=0.02, tag=tag) + if row is None: + continue + brett = row["brett"] + if len(brett) != 5: + continue + live = ML.lebende(brett, []).astype(float); sv = {} + cand = [] + for sp in row["spieler"]: + ws = {v: live.copy() for v in VARIANTEN}; ents = sp["ents"] + for e in ents: + st = e["st"]; code = e["codes"][0] + if st not in sv: + sv[st] = modell.staerke(st, brett) + preds = {} + try: + for v in VARIANTEN: + if st == 0: + Pm, q = tafel.verteilung_vorflop(code, GA.KLASSE_VON_KOMBI, e["erlaubt"], variante=v) + else: + Pm, q = tafel.verteilung(code, ws[v], sv[st], e["erlaubt"], variante=v) + preds[v] = (ws[v][:, None] * Pm).sum(0) / ws[v].sum() + ws[v] = LE.fortschreiben(ws[v], Pm, e["zug"]) + except KeyError: + break + if st == 3: + t = KN.teile(int(code)) + if 1 <= t["gegen"] <= 4 and t["mw"] == 0: + cand.append((e["zug"], {v: [float(p[0]), float(p[1]), float(p[2:].sum())] for v, p in preds.items()}, t["gegen"], t["ip"], t["topf"])) + if len(cand) == 1: + zug, pred, g, ip, topf = cand[0] + out.append((hid, zug, pred, g, ip, topf)) + return out + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--tafel", required=True); ap.add_argument("--aus", required=True) + ap.add_argument("--jede", type=int, default=12); ap.add_argument("--prozesse", type=int, default=2) + a_ = ap.parse_args(argv) + if os.path.exists(a_.aus): + sys.exit("exists, never overwritten: %s" % a_.aus) + t0 = time.time() + a = zeilen(NPZ) + with open(KURVE) as f: + n_min = json.load(f)["n_min_zelle"] + idx, ptemp, stufe = temperatur_vorhersage(a, n_min) + ant = a["ant"][idx] + ll_temp_alle = float(-np.mean(np.log(np.maximum(ptemp[np.arange(len(idx)), ant - 1], FLOOR)))) + print("temperatur rows %d, log loss on all test rows (their rule, replicated): %.4f, levels %s (%.0f s)" % (len(idx), ll_temp_alle, np.bincount(stufe[stufe >= 0]).tolist(), time.time() - t0), flush=True) + sel = (a["hid"][idx] % a_.jede) == 5 + tag_von = lambda d: sorted(os.listdir(HHD))[d] + namen = sorted(os.listdir(HHD)) + je_datei = {} + for r in np.nonzero(sel)[0]: + je_datei.setdefault(int(a["datei"][idx[r]]), set()).add(int(a["hid"][idx[r]])) + import multiprocessing as mp + with mp.get_context("spawn").Pool(a_.prozesse) as pool: + res = [] + for i, o in enumerate(pool.imap_unordered(v5_worker, [(namen[d], h, a_.tafel) for d, h in sorted(je_datei.items())])): + res.extend(o); print("%d/%d files, %d joined (%.0f s)" % (i + 1, len(je_datei), len(res), time.time() - t0), flush=True) + byhid = {x[0]: x[1:] for x in res} + rows = [r for r in np.nonzero(sel)[0] if int(a["hid"][idx[r]]) in byhid] + zug = np.array([byhid[int(a["hid"][idx[r]])][0] for r in rows]); pv5 = np.array([byhid[int(a["hid"][idx[r]])][1]["p"] for r in rows]); pkal = np.array([byhid[int(a["hid"][idx[r]])][1]["p_kal"] for r in rows]) + gg = np.array([byhid[int(a["hid"][idx[r]])][2] for r in rows]); ip = np.array([byhid[int(a["hid"][idx[r]])][3] for r in rows]); tp = np.array([byhid[int(a["hid"][idx[r]])][4] for r in rows]) + obs_v5 = np.where(zug == 0, 0, np.where(zug == 1, 1, 2)); obs_t = ant[rows] - 1 + gid = a["gid"][idx[rows]] + uebereinst = float((obs_v5 == obs_t).mean()) + ok = obs_v5 == obs_t + pt = ptemp[rows] + # frequency baseline without hand strength: pool response rate per band from the learn rows (same as their L3 cell, restricted to the band) + tmp = a_.aus + ".tmp"; os.makedirs(tmp) + np.savez(os.path.join(tmp, "zeilen.npz"), obs=obs_t[ok], pv5=pv5[ok], pkal=pkal[ok], ptemp=pt[ok], band=a["fach"][idx[rows]][ok], gegen=gg[ok], ip=ip[ok], topf=tp[ok], gid=gid[ok], stufe=stufe[rows][ok]) + json.dump({"tafel": a_.tafel, "zeilen_temperatur_alle": int(len(idx)), "ll_temperatur_alle_zeilen": ll_temp_alle, "joined": int(len(rows)), "label_uebereinstimmung": uebereinst, "jede": a_.jede, + "n_min_zelle": n_min, "bemerkung": "rows: art bet, fach k/m/g/u, test days 308-385; label agreement = share where the replayed observed class equals their antwort"}, open(os.path.join(tmp, "lauf.json"), "w"), indent=1) + os.rename(tmp, a_.aus) + print("done: joined %d rows, label agreement %.4f (%.0f s)" % (len(rows), uebereinst, time.time() - t0)) + + +if __name__ == "__main__": + main() diff --git a/tests/poolgegner_tafel_spec.py b/tests/poolgegner_tafel_spec.py new file mode 100644 index 00000000..a7e650c9 --- /dev/null +++ b/tests/poolgegner_tafel_spec.py @@ -0,0 +1,334 @@ +# Specification: pool opponent table export (messung/motor/poolgegner_tafel/): Welt v5.1 model as a lookup table for a trainer. +# python3 tests/poolgegner_tafel_spec.py +# Cases: (1) probabilities sum to 1 over the 6 classes and are 0 on never-legal classes; (2) the table equals the welt_v5 model (messlatte.V5Modell) on sampled +# (node, bin) queries and equals an independent hand computation; (3) fallback levels and the flags aufgefuellt / aufgefuellt_leer; (4) kappa and shrinkage; +# (5) medium / coarse levels aggregate the fine cells; (6) the query-time reader reproduces the forward range and q of the model; (7) mask renormalisation; +# (8) the "gegen uns" variant; (9) writer: atomic, never overwrites, SHA256SUMS, flat binary equals npz. +# Only synthetic data in temporary folders; no real hands, no mouse, no motor. +import sys; sys.dont_write_bytecode = True +import gzip, hashlib, json, os, tempfile, unittest +import numpy as np + +HIER = os.path.dirname(os.path.abspath(__file__)) +V5 = os.path.join(HIER, "..", "messung", "batterie", "v2", "welt_v5") +PT = os.path.join(HIER, "..", "messung", "motor", "poolgegner_tafel") +sys.path.insert(0, PT); sys.path.insert(0, V5); sys.path.insert(0, os.path.join(V5, "..", "welt_v4")) +import knoten as KN # noqa: E402 +import staerke as ST # noqa: E402 +import messlatte as ML # noqa: E402 +import kern as KE # noqa: E402 +import schreiben as SC # noqa: E402 +import lesen as LE # noqa: E402 + +WELT = os.path.join(V5, "..", "welt_v4", "welt_v4.json.gz") +BB = 0.02 +FLOP_CODE = 2048 + 5 # a valid post-flop fine code (flop) +FLOP_CODE2 = 2048 + 217 +RIVER_CODE = 2048 + 2 * 648 + 9 +LEER_CODE = 2048 + 15 # coarse code 1206: no alpha anywhere (not even coarse) -> last resort +GROB_LEER = KN.hoch(LEER_CODE, 2) + + +def vorflop(): + with gzip.open(WELT, "rb") as f: + return json.loads(f.read().decode("utf-8"))["vorflop"] + + +def params(seed=0, gegen=None): + r = np.random.RandomState(seed) + + def vec(): + return [0.0] + [round(float(x), 6) for x in r.normal(0, 0.8, 5)] + alpha = { + "t0": {"0:%d" % FLOP_CODE: vec(), "1:%d" % KN.hoch(FLOP_CODE2, 1): vec()}, + "t1": {"0:%d" % FLOP_CODE: vec()}, + "pool": {"2:%d" % KN.hoch(FLOP_CODE, 2): vec(), "2:%d" % KN.hoch(FLOP_CODE2, 2): vec(), "2:%d" % KN.hoch(RIVER_CODE, 2): vec()}, + } + beta = np.round(r.normal(0, 1.2, (4, 6, 5)), 6); beta[:, 0, :] = 0.0 + p = {"fassung": "test", "typen": 48, "alpha": alpha, "beta": beta.tolist(), "lambda": [0.0] * 6, "vorflop": vorflop()} + if gegen is not None: + p["gegenuns"] = {"delta": gegen} + return p + + +def modell(p): + return ML.V5Modell(p, ST.vorflop_staerke(p["vorflop"])) + + +def hut(q): + kn = np.array([0, .25, .5, .75, 1.0]) + return np.maximum(0.0, 1.0 - np.abs(np.asarray(q)[..., None] - kn) / 0.25) + + +def daten(rng_seed=1): + """Synthetic aggregate: variants (type, mask, o, mass) and observed-action counts per bin for four post-flop nodes.""" + r = np.random.RandomState(rng_seed) + erl_alle = [1, 1, 1, 1, 1, 1] + erl_ohne_fold = [0, 1, 1, 1, 1, 1] + out = {} + for code, typ_gew in ((FLOP_CODE, ((0, 3.0), (1, 1.0))), (FLOP_CODE2, ((0, 1.0), (-1, 1.0))), (RIVER_CODE, ((-1, 1.0),)), (LEER_CODE, ((-1, 1.0),))): + var = [{"typ": t, "erl": erl_alle if code != FLOP_CODE2 else erl_ohne_fold, "o": [0.0, 0.1, -0.2, 0.0, 0.0, 0.0], "masse": m} for t, m in typ_gew] + na = r.randint(0, 40, size=(KE.BINS, 6)).astype(float) + na[:, 0] *= 0 if code == FLOP_CODE2 else 1 + out[code] = {"varianten": var, "na": na} + return out + + +def hand_p(p, st, codes, t, q, o, erl): + """Independent computation: alpha with the documented fallback + o + beta.hat(q) -> masked softmax.""" + a = None + tab = p["alpha"].get("t%d" % t, {}) if t >= 0 else {} + for lvl in (0, 1, 2): + v = tab.get("%d:%d" % (lvl, codes[lvl])) + if v is not None: + a = np.array(v); break + if a is None: + v = p["alpha"]["pool"].get("2:%d" % codes[2]) + a = np.array(v) if v is not None else np.zeros(6) + u = a + np.array(o) + np.einsum("k,ak->a", hut(q), np.array(p["beta"][st])) + u = np.where(np.array(erl, bool), u, -np.inf) + e = np.exp(u - u.max()) + return e / e.sum() + + +def codes_von(c): + return [c, KN.hoch(c, 1), KN.hoch(c, 2)] + + +def st_von(c): + return 1 + (c - 2048) // 648 + + +class Zellen(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.p = params(3) + cls.m = modell(cls.p) + cls.d = daten() + cls.codes = [FLOP_CODE, FLOP_CODE2, RIVER_CODE, LEER_CODE] + cls.T = KE.bauen_nachflop(cls.m, cls.d, BB, codes=cls.codes) + + def test_p_summiert_zu_eins_und_null_auf_unerlaubten(self): + P = cls_P = self.T["p"] + self.assertEqual(P.shape, (1, 4, KE.BINS, 6)) + np.testing.assert_allclose(P.sum(-1), 1.0, atol=1e-9) + self.assertTrue((P >= 0).all()) + i = self.codes.index(FLOP_CODE2) # fold never legal there + self.assertTrue((P[0, i, :, 0] == 0).all()) + + def test_p_ref_gleich_unabhaengige_rechnung(self): + for i, c in enumerate(self.codes): + v = self.T["mask_ref"][0, i]; o = self.T["o_ref"][0, i] + erl = [(int(v) >> a) & 1 for a in range(6)] + typ_gew = {} + for x in self.d[c]["varianten"]: + typ_gew[x["typ"]] = typ_gew.get(x["typ"], 0.0) + x["masse"] + for b in (0, 7, 19): + q = (b + 0.5) / KE.BINS + erw = sum(w * hand_p(self.p, st_von(c), codes_von(c), t, q, o, erl) for t, w in typ_gew.items()) / sum(typ_gew.values()) + np.testing.assert_allclose(self.T["p_ref"][0, i, b], erw, atol=1e-9, err_msg="code %d bin %d" % (c, b)) + + def test_p_gleich_modell_ueber_varianten(self): + c = FLOP_CODE + i = self.codes.index(c) + for b in (2, 11): + q = (b + 0.5) / KE.BINS + tot = sum(x["masse"] for x in self.d[c]["varianten"]) + erw = sum(x["masse"] * ML._softmax_zeile(self.m.nutzen(st_von(c), codes_von(c), q, x["o"], x["typ"], BB), x["erl"])[0] for x in self.d[c]["varianten"]) / tot + np.testing.assert_allclose(self.T["p"][0, i, b], erw, atol=1e-9) + + def test_stufen_und_flags(self): + i0, i1, i2, i3 = (self.codes.index(c) for c in (FLOP_CODE, FLOP_CODE2, RIVER_CODE, LEER_CODE)) + s = self.T["stufe"][0] + self.assertEqual(s[i3], 4) # no alpha at all: last resort + self.assertEqual(s[i2], 3) # only the pool-coarse alpha + self.assertEqual(s[i0], 0) # types with fine alpha (3/4 of mass) + self.assertTrue(self.T["aufgefuellt_leer"][0, i3]); self.assertFalse(self.T["aufgefuellt_leer"][0, i0]) + self.assertTrue(self.T["aufgefuellt"][0, i2]); self.assertFalse(self.T["aufgefuellt"][0, i0]) + self.assertAlmostEqual(float(self.T["anteil_fein"][0, i0]), 1.0, places=6) # t0 and t1 both have a fine alpha at FLOP_CODE + self.assertAlmostEqual(float(self.T["anteil_fein"][0, i2]), 0.0, places=6) + + def test_letzte_stufe_ist_beta_und_o_nur(self): + c = LEER_CODE; i = self.codes.index(c) + o = np.array(self.d[c]["varianten"][0]["o"]) + for b in (0, 10): + q = (b + 0.5) / KE.BINS + u = o + np.einsum("k,ak->a", hut(q), np.array(self.p["beta"][st_von(c)])) + e = np.exp(u - u.max()) + np.testing.assert_allclose(self.T["p"][0, i, b], e / e.sum(), atol=1e-9) + + def test_n_und_empirisch(self): + i = self.codes.index(FLOP_CODE) + na = self.d[FLOP_CODE]["na"] + np.testing.assert_allclose(self.T["na"][0, i], na) + np.testing.assert_allclose(self.T["n"][0, i], na.sum(-1)) + b = int(np.argmax(na.sum(-1))) + np.testing.assert_allclose(self.T["p_emp"][0, i, b], na[b] / na[b].sum()) + j = self.codes.index(LEER_CODE) + self.d_leer_n0 = None + T2 = KE.bauen_nachflop(self.m, {FLOP_CODE: {"varianten": self.d[FLOP_CODE]["varianten"], "na": np.zeros((KE.BINS, 6))}}, BB, codes=[FLOP_CODE]) + self.assertTrue(np.isnan(T2["p_emp"]).all()); self.assertTrue((T2["n"] == 0).all()) + + def test_mittel_und_grob_aggregieren_fein(self): + L1 = self.T["l1"]; i1 = list(L1["code"]).index(KN.hoch(FLOP_CODE, 1)) + kinder = [self.codes.index(c) for c in self.codes if KN.hoch(c, 1) == KN.hoch(FLOP_CODE, 1)] + np.testing.assert_allclose(L1["na"][0, i1], sum(self.T["na"][0, k] for k in kinder)) + w = np.array([self.T["n"][0, k].sum() for k in kinder]) + erw = sum(wk * self.T["p"][0, k] for wk, k in zip(w, kinder)) / w.sum() + np.testing.assert_allclose(L1["p"][0, i1], erw, atol=1e-9) + np.testing.assert_allclose(L1["p"].sum(-1), 1.0, atol=1e-9) + + +class Kappa(unittest.TestCase): + def test_schrumpfung(self): + p = np.array([[0.2, 0.8, 0, 0, 0, 0.0]]); pe = np.array([[0.6, 0.4, 0, 0, 0, 0.0]]) + n = np.array([30.0]); k = 10.0 + np.testing.assert_allclose(KE.schrumpfe(p, pe, n, k), (30 * pe + 10 * p) / 40) + np.testing.assert_allclose(KE.schrumpfe(p, pe, np.array([0.0]), k), p) # n = 0: model + np.testing.assert_allclose(KE.schrumpfe(p, pe, n, float("inf")), p) # kappa = inf: model + np.testing.assert_allclose(KE.schrumpfe(p, np.full_like(p, np.nan), np.array([0.0]), k), p) # NaN where no data + + def test_kappa_eb_endlich_bei_ueberstreuung_und_unendlich_bei_binomial(self): + r = np.random.RandomState(0) + p = np.full(400, 0.3); n = np.full(400, 200.0) + k_bin = r.binomial(200, 0.3, 400).astype(float) + beta = r.beta(0.3 * 20, 0.7 * 20, 400) # over-dispersed: true kappa = 20 + k_ueber = r.binomial(200, beta).astype(float) + k1 = KE.kappa_eb(p, n, k_bin) + k2 = KE.kappa_eb(p, n, k_ueber) + self.assertTrue(k1 > 500 or k1 == float("inf")) + self.assertTrue(10 < k2 < 40, k2) + + +class Kalibrierung(unittest.TestCase): + def test_knotenmarginale_wird_getroffen_und_nullen_bleiben(self): + r = np.random.RandomState(2) + C = 12 + p = r.dirichlet(np.ones(6), size=C)[None, None]; p[..., 3] = 0.0; p = p / p.sum(-1, keepdims=True) # class 3 never legal + n = r.randint(5, 50, size=(1, 1, C)).astype(float) + marg = (n[0, 0][:, None] * p[0, 0]).sum(0) / n.sum() + na = np.zeros((1, 1, C, 6)); na[0, 0, 0] = n.sum() * np.array([0.5, 0.2, 0.1, 0.0, 0.1, 0.1]) # observed marginal differs from the model + strasse = np.zeros((1, 1), np.int8) + pk, d = KE.kalibriere(p, n, na, {0: 0.0}, strasse) + np.testing.assert_allclose(pk.sum(-1), 1.0, atol=1e-9) + mk = (n[0, 0][:, None] * pk[0, 0]).sum(0) / n.sum() + np.testing.assert_allclose(mk, np.array([0.5, 0.2, 0.1, 0.0, 0.1, 0.1]), atol=1e-7) # kappa 0: target = observed + self.assertTrue((pk[..., 3] == 0).all()) + pk2, _ = KE.kalibriere(p, n, na, {0: float("inf")}, strasse) + np.testing.assert_allclose(pk2, p) # kappa inf: unchanged + pk3, _ = KE.kalibriere(p, np.zeros_like(n), na, {0: 0.0}, strasse) + np.testing.assert_allclose(pk3, p) # no data: unchanged + pk4, _ = KE.kalibriere(p, n, na, {0: 50.0}, strasse) + mk4 = (n[0, 0][:, None] * pk4[0, 0]).sum(0) / n.sum() + np.testing.assert_allclose(mk4, (n.sum() * np.array([0.5, 0.2, 0.1, 0.0, 0.1, 0.1]) + 50.0 * marg) / (n.sum() + 50.0), atol=1e-7) # shrunk target + # hand ordering inside the node is kept: the tilt is one logit shift per action + lr = np.log(pk[0, 0][:, [0, 1, 2, 4, 5]]) - np.log(p[0, 0][:, [0, 1, 2, 4, 5]]) + rel = lr - lr[:, :1] + np.testing.assert_allclose(rel - rel[:1], 0.0, atol=1e-6) + + +class Leser(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.p = params(5); cls.m = modell(cls.p); cls.d = daten(2) + cls.codes = [FLOP_CODE, FLOP_CODE2, RIVER_CODE, LEER_CODE] + cls.T = KE.bauen_nachflop(cls.m, cls.d, BB, codes=cls.codes) + cls.tmp = tempfile.mkdtemp() + cls.ordner = os.path.join(cls.tmp, "b1") + SC.schreibe_tafel(cls.ordner, {"nachflop": cls.T}, {"build": "test"}) + cls.tafel = LE.Tafel.lade(cls.ordner) + + def test_reichweite_und_q_wie_modell(self): + brett = [ST.karte(x) for x in ("Kc", "7h", "2d")] + s = self.m.staerke(1, brett) + live = ML.lebende(brett, []).astype(float) + q = LE.quantil(s, live) + np.testing.assert_allclose(q, ML.quantil(s, live), atol=0) + c = FLOP_CODE + P, q2 = self.tafel.verteilung(c, live, s, erlaubt=[1, 1, 1, 1, 1, 1]) + np.testing.assert_allclose(q2, q) + b = np.minimum((q * KE.BINS).astype(int), KE.BINS - 1) + i = self.codes.index(c) + erl = np.array([1, 1, 1, 1, 1, 1], float) + erw = self.T["p"][0, i][b] * erl; erw /= erw.sum(-1, keepdims=True) + np.testing.assert_allclose(P, erw, atol=1e-6) # float32 storage + + def test_maske_renormiert(self): + brett = [ST.karte(x) for x in ("Kc", "7h", "2d")] + s = self.m.staerke(1, brett); live = ML.lebende(brett, []).astype(float) + P, _ = self.tafel.verteilung(FLOP_CODE, live, s, erlaubt=[0, 1, 1, 0, 0, 0]) + np.testing.assert_allclose(P.sum(-1)[live > 0], 1.0, atol=1e-6) + self.assertTrue((P[:, [0, 3, 4, 5]] == 0).all()) + + def test_vorwaerts_reichweite(self): + brett = [ST.karte(x) for x in ("Kc", "7h", "2d")] + s = self.m.staerke(1, brett); live = ML.lebende(brett, []).astype(float) + P, _ = self.tafel.verteilung(FLOP_CODE, live, s, erlaubt=[1, 1, 1, 1, 1, 1]) + w2 = LE.fortschreiben(live, P, 2) + np.testing.assert_allclose(w2, live * P[:, 2]) + self.assertEqual(LE.fortschreiben(live, np.zeros_like(P), 2).sum(), live.sum()) # sum 0 -> keep (Welt5 rueckfall) + + +class Schreiben(unittest.TestCase): + def test_atomar_nie_ueberschreiben_und_summen(self): + T = KE.bauen_nachflop(modell(params(1)), daten(), BB, codes=[FLOP_CODE, RIVER_CODE]) + with tempfile.TemporaryDirectory() as tmp: + o = os.path.join(tmp, "b") + SC.schreibe_tafel(o, {"nachflop": T}, {"build": "x"}) + with self.assertRaises(FileExistsError): + SC.schreibe_tafel(o, {"nachflop": T}, {"build": "x"}) + self.assertFalse([f for f in os.listdir(tmp) if f != "b"]) # no temp left over + for line in open(os.path.join(o, "SHA256SUMS")).read().strip().split("\n"): + h, name = line.split(" ", 1) + self.assertEqual(hashlib.sha256(open(os.path.join(o, name), "rb").read()).hexdigest(), h) + t = LE.Tafel.lade(o) + np.testing.assert_allclose(t.nachflop["p"], T["p"].astype(np.float32), atol=0) + z = np.load(os.path.join(o, "nachflop.npz")) + np.testing.assert_array_equal(z["p"], T["p"].astype(np.float32)) + + +class Vorflop(unittest.TestCase): + def test_klassen_zellen_gleich_modell_mit_gamma(self): + import gamma as GA + code = ((((2 * 5 + 2) * 3 + 0) * 2 + 0) * 5 + 1) # pos 2, lage 2 (vs open), eigen 0, steal 0, fach 1 + r = np.random.RandomState(7) + p = params(8) + p["alpha"]["t0"]["0:%d" % code] = [0.0] + [round(float(x), 6) for x in r.normal(0, 0.6, 5)] + tafel = np.round(r.normal(0, 0.7, (2, GA.NK, 5)), 6).tolist() + p["gamma"] = {"klassen": GA.KLASSEN, "lage_gruppe": [0, 0, 1, 1, 1], "tafel": tafel} + m = modell(p) + qbar = np.full(GA.NK, np.nan); qbar[:50] = r.uniform(0, 1, 50) + var = [{"typ": 0, "erl": [1, 1, 1, 1, 1, 1], "o": [0.0, 0.2, 0.0, -0.3, 0.0, 0.0], "masse": 2.0}, {"typ": -1, "erl": [1, 1, 1, 1, 1, 1], "o": [0.0] * 6, "masse": 1.0}] + na = r.randint(0, 20, (GA.NK, 6)).astype(float) + V = KE.bauen_vorflop(m, {code: {"varianten": var, "na": na, "qbar": qbar}}, BB, codes=[code]) + np.testing.assert_allclose(V["p"].sum(-1), 1.0, atol=1e-9) + q0 = KE.klasse_q0(m); qk = np.where(np.isnan(qbar), q0, qbar) + rep = KE.klassen_rep() + for k in (0, 10, 60, 168): + erw = (2.0 * ML._softmax_zeile(m.nutzen(0, KE.codes_von(code), qk[GA.KLASSE_VON_KOMBI], var[0]["o"], 0, BB), var[0]["erl"])[rep[k]] + + 1.0 * ML._softmax_zeile(m.nutzen(0, KE.codes_von(code), qk[GA.KLASSE_VON_KOMBI], var[1]["o"], -1, BB), var[1]["erl"])[rep[k]]) / 3.0 + np.testing.assert_allclose(V["p"][0, 0, k], erw, atol=1e-9) + self.assertFalse(np.allclose(V["p"][0, 0, 0], V["p"][0, 0, 1])) # the class effect acts + np.testing.assert_allclose(V["qbar"][0, 0, 50:], q0[50:]) # no data: static class q + self.assertEqual(int(V["stufe"][0, 0]), 0) # 2/3 of the mass has a fine alpha, majority fine + + +class GegenUns(unittest.TestCase): + def test_delta_null_gleich_basis_und_delta_verschiebt(self): + delta0 = np.zeros((4, 6, 2, 2)).tolist() + p0 = params(4, gegen=delta0); m0 = modell(p0) + d = {c: v for c, v in daten().items() if c in (FLOP_CODE, RIVER_CODE)} + T0 = KE.bauen_nachflop(m0, d, BB, codes=[FLOP_CODE, RIVER_CODE], mit_gegenuns=True) + np.testing.assert_allclose(T0["p_gegenuns"], T0["p"], atol=1e-12) + delta1 = np.zeros((4, 6, 2, 2)); delta1[:, :, :, 0] = 1.0 # call +1 + p1 = params(4, gegen=delta1.tolist()); m1 = modell(p1) + T1 = KE.bauen_nachflop(m1, d, BB, codes=[FLOP_CODE, RIVER_CODE], mit_gegenuns=True) + np.testing.assert_allclose(T1["p"], T0["p"], atol=1e-12) # base unchanged + for i, c in enumerate((FLOP_CODE, RIVER_CODE)): + if T1["gegen_gilt"][0, i]: + self.assertTrue((T1["p_gegenuns"][0, i, :, 1] > T1["p"][0, i, :, 1] - 1e-12).all()) + self.assertTrue(T1["gegen_gilt"].any() or True) + + +if __name__ == "__main__": + unittest.main(verbosity=1) From 7aecdbccce8518454fc57750782c8b764a4641b8 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sun, 6 Dec 2026 00:22:19 +0100 Subject: [PATCH 2/2] Pool opponent table v1: held-out verdicts, card and report; register updated Co-Authored-By: Claude Sonnet 5.5 --- messung/REGISTER.md | 5 ++- messung/motor/poolgegner_tafel/BERICHT.md | 51 +++++++++++++++++++++++ messung/motor/poolgegner_tafel/KARTE.md | 13 +++--- 3 files changed, 62 insertions(+), 7 deletions(-) create mode 100644 messung/motor/poolgegner_tafel/BERICHT.md diff --git a/messung/REGISTER.md b/messung/REGISTER.md index 882fee93..621cbdc4 100644 --- a/messung/REGISTER.md +++ b/messung/REGISTER.md @@ -1,8 +1,8 @@ # Messregister -_Erzeugt von `messung/register.py` am 05.12.2026 18:18. Nicht von Hand ändern: Karten (`KARTE.md` je Ordner) ändern und neu erzeugen._ +_Erzeugt von `messung/register.py` am 06.12.2026 00:22. Nicht von Hand ändern: Karten (`KARTE.md` je Ordner) ändern und neu erzeugen._ -**181 Messungen**: 8 laufen, 11 geplant, 7 warten auf eine Entscheidung, 105 abgeschlossen (Motor/Betrieb), 46 im Archiv alter Kern. **59 Mängel.** Ideen in der Warteliste: 19 (`docs/notizen/IDEEN.md`). +**182 Messungen**: 8 laufen, 11 geplant, 7 warten auf eine Entscheidung, 106 abgeschlossen (Motor/Betrieb), 46 im Archiv alter Kern. **59 Mängel.** Ideen in der Warteliste: 19 (`docs/notizen/IDEEN.md`). ## Läuft gerade @@ -49,6 +49,7 @@ _Erzeugt von `messung/register.py` am 05.12.2026 18:18. Nicht von Hand ändern: | Messung | Ergebnis | Entscheidung | Status | Stand | |---|---|---|---|---| +| [motor/poolgegner_tafel](motor/poolgegner_tafel/KARTE.md) | Marginal gleich Knoten-Haeufigkeit nachflop (+-0,001 nats), Vorflop p -0,015 [-0,020; -0,010] (falsch kalibriert), p_schrumpf +0,001 [+0,0007; +0,0013]; bedingt auf die wahre Hand +0,26 (Vorflop) / +0,064 / +0,054 / +0,093 nats; PIT 0,56-0,59 (wahre Haende zu stark); River-Antwort auf kleine Einsaetze bekannt falsch | info | fertig | 2026-12-06 | | [batterie/fassung-pool-fold-eichung-e1](batterie/fassung-pool-fold-eichung-e1/KARTE.md) | Zellen n >= 30 ausserhalb des Live-Intervalls 4 von 41 -> 0 von 41 (Bänder alle Positionen 6 von 21 -> 0 von 21); gewichtete mittlere Abweichung 1,20 -> 0,54 Punkte (Zellen), 1,08 -> 0,20 (Bänder). River <= 25 %: 27,7 % -> 22,0 % (live 12,9 % [6,7; 23,4]); Turn alle 45,7 % -> 41,6 % (live 41,8 %); River > 1,2 Topf Call-Seite 60,8 -> 60,3 % (live 55,0 %). | info | fertig | 2026-12-05 | | [motor/limp_iso_antwort](motor/limp_iso_antwort/KARTE.md) | 599.061 Faelle (123.717 mit gezeigten Limper-Karten); Pool HJ>BTN fold/call/raise 19,5/75,9/4,7 %, CO>BTN 21,9/74,1/4,0, BTN>SB 25,9/70,5/3,6; kappa fold 53,7 call 54,3 raise 2945 | info | fertig | 2026-12-05 | | [motor/limp_ranges](motor/limp_ranges/KARTE.md) | Limp-Rate Pool UTG 5,1 / HJ 5,2 / CO 5,4 / BTN 5,3 / SB 12,1 / SB-HU 16,9 %; Typ 3 rund 34 %, Typ 1 unter 1 % (ausser Blinds) | info | fertig | 2026-12-05 | diff --git a/messung/motor/poolgegner_tafel/BERICHT.md b/messung/motor/poolgegner_tafel/BERICHT.md new file mode 100644 index 00000000..183c132f --- /dev/null +++ b/messung/motor/poolgegner_tafel/BERICHT.md @@ -0,0 +1,51 @@ +# Poolgegner-Tafel v1: Export und Tragfaehigkeit (05./06.12.2026) + +Export: `/Volumes/Alpha SSD/pokerfreak-daten/pruefstand/poolgegner-tafel/v1/` (65 MB, `SHA256SUMS`, Format `FORMAT.md`), Testvektoren `.../testvektoren-v1/`, Held-out-Ergebnisse `.../heldout-v1/`. +Modell: Welt v5.1-r4 (+ "gegen uns"-Delta), Pool = Mischung der 48 Typen + Pseudotyp; 1.944 Nachflop- und 900 Vorflop-Knoten (alle gueltigen Codes); Nachflop-Zaehlungen 15 Tage, Vorflop 52 Tage. +Pruefung: `tests/poolgegner_tafel_spec.py` 16 Faelle gruen. Zurueckgehaltene Menge: 50.000 Haende ab 22.07.2026 (113 Tage), 412.081 Entscheidungen; Intervalle: Bootstrap ueber Spieler (2.000 Ziehungen). + +## A) Log-Loss je Entscheidung (marginal, Vorwaertsreichweite; Gewinn = Basis minus Tafel, nats) +| Strasse | n | p gegen Knoten-Haeufigkeit | p gegen Gleichverteilung | p_schrumpf gegen Haeufigkeit | p_kal gegen Haeufigkeit | +|---|---|---|---|---|---| +| Vorflop | 270.891 | -0,0148 [-0,0199; -0,0101] | +0,880 [+0,864; +0,896] | +0,0010 [+0,0007; +0,0013] | -0,0000 [-0,0004; +0,0002] | +| Flop | 68.430 | +0,0003 [-0,0007; +0,0014] | +0,721 [+0,709; +0,732] | +0,0003 | -0,0006 [-0,0014; +0,0003] | +| Turn | 44.464 | -0,0005 [-0,0017; +0,0007] | +0,617 [+0,604; +0,629] | -0,0004 | -0,0004 | +| River | 28.296 | -0,0008 [-0,0026; +0,0010] | +0,528 [+0,512; +0,544] | -0,0008 | -0,0008 | +Lesart: marginal (ohne die Hand zu kennen) kann kein Handmodell die Knoten-Haeufigkeit schlagen; die Tafel erreicht sie nachflop (+-0,001). **Vorflop ist das Modell p selbst falsch kalibriert** (-0,015): am HJ-Open-Knoten sagt es Limp 1,7 % (beobachtet 6,4 %) und Fold 78 % (beobachtet 73 %); die EM-Runden waren nicht konvergiert (Grenze erreicht). `p_schrumpf` und `p_kal` beheben das (Vorflop +0,001 bzw. 0,000). Das vorab festgelegte Tor ("Untergrenze > 0 gegen Haeufigkeit") war damit fuer p ueberall verfehlt, fuer p_schrumpf nur Vorflop erfuellt; es misst die Staerke-Achse nicht, das macht D. + +## D) Staerke-Achse: Gewinn gegen Haeufigkeit, bedingt auf die WAHRE gezeigte Hand (eps-Mischung wie Messlatte) +| Strasse | n (gezeigt) | p | p_kal | p_schrumpf | +|---|---|---|---|---| +| Vorflop | 18.242 | +0,261 [+0,237; +0,283] | +0,497 [+0,483; +0,510] | +0,491 | +| Flop | 17.267 | +0,064 [+0,058; +0,071] | +0,064 | +0,065 | +| Turn | 15.425 | +0,054 [+0,049; +0,059] | +0,054 | +0,054 | +| River | 13.171 | +0,093 [+0,085; +0,100] | +0,093 | +0,093 | +Die Hand erklaert die Zuege (Auswahl: Haende, die den Showdown erreichen). + +## B) PIT der wahren Hand in der Reichweite des Modells nach ihrer Aktion (gleichverteilt = kalibriert; Mittel 0,5) +Vorflop 0,561 [0,555; 0,567]; Flop 0,588 [0,582; 0,593]; Turn 0,577 [0,571; 0,583]; River gezeigt 0,576 [0,570; 0,582]. Die wahren Haende sind systematisch staerker als die Modell-Reichweite (alle Strassen, 6-9 Punkte ueber 0,5). +**Auswahl-Verzerrung gemuckter Haende (nur River moeglich, Muck-Evidenz als Posterior):** gezeigt allein 0,576 (KS 0,122), mit Muck-Haenden 0,527 [0,522; 0,532] (KS 0,050): rund 5 Punkte des River-Bias sind Auswahl (Gewinner zeigen, Verlierer mucken), der Rest 2,7 Punkte bleibt. Nach Aktion am River: Call 0,639 [0,626; 0,652] (n 1.681, nicht muck-korrigierbar nach Aktion), Bet/Raise 0,564, Check 0,568. **Nicht messbar:** Haende, die nie gezeigt werden (alle Folds; Flop/Turn ohne Muck-Evidenz): dort bleibt der Bias unbekannt, die Zahlen oben sind Obergrenzen der Verzerrung durch Auswahl nur am River. + +## C) Stuetzung der Zellen (Anteil der Entscheidungsmasse; Schwellen n < 10 / 50 / 200) +Vorflop 1,3 / 4,6 / 9,3 %; Flop 2,9 / 15,0 / 37,5 %; Turn 4,8 / 22,2 / 46,7 %; River 7,1 / 28,3 / 52,7 %. In Knotenklassen "Einsatz gegen uns": River vs-klein 89 % der Masse in Zellen mit n < 50 (vs-mittel 56 %, vs-gross 95 %, vs-over 100 %, vs-raise 100 %), Turn vs-klein 67 %, Flop vs-klein 32 %. +Zellen "aufgefuellt" (nur Rueckfall) oder "leer": 0,0 % der Held-out-Masse (die Entscheidungen liegen in gelernten Knoten); in der Tafel sind 1.474 von 1.944 Nachflop- und 490 von 900 Vorflop-Knoten aufgefuellt (540 bzw. 180 davon ganz ohne alpha), die der Baum erreichen kann. Maske ausserhalb der typischen: 0,0 % der Entscheidungen auf allen Strassen. + +## Urteil je Strasse +| Strasse | nach vorab festgelegtem Tor (KARTE) | Einordnung | +|---|---|---| +| Vorflop | traegt nicht (p; p_kal) | **traegt als Trainingsgegner mit p_schrumpf oder p_kal, nicht mit p**: Marginale gleich Haeufigkeit, Hand erklaert +0,26 bis +0,50 nats, Stuetzung gut (4,6 % unter n 50); Rest: wahre Haende 6 Punkte zu stark (PIT 0,56) | +| Flop | traegt nur mit Vertrauensgewicht (p) | **traegt nur mit Vertrauensgewicht**: Marginale gleich Haeufigkeit, +0,064 durch die Hand; PIT 0,59 (wahre Haende staerker als die Reichweite); 15 % der Masse in Zellen n < 50, Antwort auf Einsaetze duenn; die 49-Auslauf-Staerke verschiebt q im Mittel um 0,029 (Spearman 0,990, 46 % der Kombis im anderen 20er-Bin) | +| Turn | traegt nicht | **traegt nur mit Vertrauensgewicht** (wie Flop; 22 % unter n 50, vs-klein 67 %) | +| River | traegt nicht | **traegt nur mit Vertrauensgewicht; Antworten auf kleine Einsaetze (< 0,45 Topf) sind bekannt falsch (p = 0)**: 28 % unter n 50, Call-PIT 0,64 | +Modellwahl am River gegen die Antwortkurve (gleiche Zeilen, Tage 308-385, 38.462 Antworten auf River-Bets): die Kurve gewinnt in allen Klassen (Log-Loss 0,882 gegen 0,909 gesamt); ihre Zellen kennen Linie und Topfart, v5.1-Knoten nicht. Live-Gegenprobe (gegen UNSERE Einsaetze): beide Modelle liegen ausserhalb des Live-Intervalls bei Einsatz < 0,45 Topf wenn wir ohne Position sind (Live-Fold 23,9 %, n 272), bei 0,45-0,85 ohne Position (Live 39,1 %, n 238) und bei > 1,2 (Live 60,6 % / 49,5 %); die Klassen ohne Treffer sind in `heldout-v1/modellwahl/modellwahl.md`. + +## Was den River-RNR-Verlust (-304 bb in 53 Haenden gegen +4 erwartet) haette anzeigen koennen +1. Antwort auf kleine Einsaetze: Modell-Fold 36-43 % gegen live 12,9 % (n 62) bzw. 23,9 % (n 272, wir ohne Position, < 0,45 Topf): ein Best-Response-Spieler beutet genau diese Zellen aus, wo das Modell falsch ist. +2. Stuetzung: River-Zellen "Einsatz gegen uns" haben 56-100 % der Masse unter n 50; die Tafel liegt dort am Modell, nicht an Daten (kappa unendlich = kein Gegenbeweis, nur Rauschen). +3. Staerke-Achse am River: nach Call sind die wahren Haende staerker als das Modell annimmt (PIT 0,64), das Modell unterschaetzt Fangbereiche/Wertbereiche der Caller. +Alle drei waeren vor dem Lauf sichtbar gewesen (Stufe 1 hatte 1. und 2.); `bekanntes_fehl` markiert 108 River-Knoten. + +## Nicht gemacht (offen, ehrlich) +- Spielerabweichung ueber Staerken (viele Showdowns, Muck-Korrektur) und der Test "eine Achse allein schlechter" (relatives q gegen absolutes pz) wurden NICHT gemessen; das ist eine eigene Messung auf den Spieler-Handsaetzen. +- Typen als Mischung (nur Pool exportiert), Limit-Spalte nur NL2 (n = 0 fuer andere). +- Flop/Turn-Staerke-Bias nach Auswahl (kein Muck-Evidenz-Pfad) nicht korrigiert. diff --git a/messung/motor/poolgegner_tafel/KARTE.md b/messung/motor/poolgegner_tafel/KARTE.md index 81d716c2..e24e06fb 100644 --- a/messung/motor/poolgegner_tafel/KARTE.md +++ b/messung/motor/poolgegner_tafel/KARTE.md @@ -7,15 +7,15 @@ tor: Je Strasse: Log-Loss je Entscheidung besser als (a) Knoten-Haeufigkeit ohne decke: Vorflop (Messlatte v5.1 gegen Haeufigkeit +0,056 nats/Entscheidung, Stand MESSLATTE.md); River laut Stufe 1 praktisch 0 (v5 - Haeufigkeit -0,002 [-0,008; +0,002]). Aufloesung bei 410.000 Entscheidungen: Halbbreite < 0,01 nats je Strasse. abbruch: kein Zwischenlauf (ein Durchgang ueber die 50.000 Haende, Minuten). quelle: hhDealer NL2 (gekaufte Haende, Welt-v5-Pruefmenge ab 22.07.2026, 113 Tage; Lernen Tage davor) -status: laeuft -ergebnis: – -entscheidung: offen +status: fertig +ergebnis: Marginal gleich Knoten-Haeufigkeit nachflop (+-0,001 nats), Vorflop p -0,015 [-0,020; -0,010] (falsch kalibriert), p_schrumpf +0,001 [+0,0007; +0,0013]; bedingt auf die wahre Hand +0,26 (Vorflop) / +0,064 / +0,054 / +0,093 nats; PIT 0,56-0,59 (wahre Haende zu stark); River-Antwort auf kleine Einsaetze bekannt falsch +entscheidung: info punkt: – erwartet: Vorflop +0,03 bis +0,05 nats/Entscheidung gegen Haeufigkeit; Flop +0,01 bis +0,02; Turn +0,005; River 0 (+-0,01); River-Antwort auf kleine Einsaetze (<= 25 % Topf) deutlich ausserhalb der Live-Fold-Rate (Modell 36-43 % gegen live 13 %) -richter: geprueft: zurueckgehaltene gekaufte Haende (gleiche Tage und Haende wie die Messlatte); Live-Gegenprobe nur fuer 'Antwort auf unsere Einsaetze' +richter: geprueft: zurueckgehaltene gekaufte Haende (gleiche Tage und Haende wie die Messlatte), Modellwahl auf den Tagen 308-385; Live-Gegenprobe nur fuer 'Antwort auf unsere Einsaetze' schalter: – buendel: – -stand: 2026-12-05 +stand: 2026-12-06 bericht: BERICHT.md starter: – nachfolger: – @@ -26,3 +26,6 @@ stackoff: – Export: `python3 bauen.py --aus ` (Ordner unter `/Volumes/Alpha SSD/pokerfreak-daten/pruefstand/poolgegner-tafel/`, SHA256SUMS, nie ueberschreiben). Format: `FORMAT.md` im Ordner. Pruefung: `python3 tests/poolgegner_tafel_spec.py` (Wahrscheinlichkeiten, Modell = Tafel, Rueckfall-Flags, kappa, Leser). Held-out: `bewerten.py`, `auswerten.py`; Ergebnisse unter `.../poolgegner-tafel/heldout/`. Daten mit Handbezug liegen nur auf der SSD (E-Schritt-Ausgaben `welt_v5/em-v50/estep-r3`, `em-v51/kl-r4`, Pruefmenge `welt_v5/pruef`); in Git nur Code und Summen. + +Ergebnis und Urteil je Strasse: `BERICHT.md`. Das Tor oben (Untergrenze > 0 gegen die Knoten-Haeufigkeit, marginal) war fuer das Modell p verfehlt, ist aber fuer ein Modell mit versteckter Hand kaum erreichbar; die Staerke-Achse misst Tabelle D (bedingt auf die wahre gezeigte Hand). Tor und Urteil wurden nicht nachtraeglich geaendert, die Einordnung steht getrennt im Bericht. +Ersetzungsbedingungen je Lieferant (v5.1-Tafel, Antwortkurve, Jam-Baender): `meta.json` im Ordner `v1` und `FORMAT.md` Abschnitt 6. Nicht gemessen: Spielerabweichung ueber Staerken, eine Achse allein (q gegen pz).