#!/usr/bin/env python3 """Stack-off-Ranges des Kerns gegen die echten NL2-Gewinner, auf echten hhDealer-Vorflop-Spots (A-Tische, kein Splash im Bestand), bepreist aus ALLEN Haenden des Knotens. Modellfrei bis auf die Klassen-Equity-Matrix; kein Zwilling. Spot = eine echte Vorflop-Entscheidung eines Spielers, dessen Karten in der Hand gezeigt wurden, effektiv >= 20 bb, und - gegen eine 3-Bet oder hoeher (Stufe >= 2), oder - gegen ein All-in (jede Stufe), oder - eigene 3-Bet / eigener Jam gegen ein Open, oder ein Open-Jam. Der Kern bekommt die echte Lage (Live-Format, ohne Gegnerprofil) mit den echten Karten. Verglichen wird seine Aktion (FOLD / CALL / RAISE / JAM) mit der echten, getrennt nach Gewinnern und Feld. Preis je Aktion (bb ab jetzt, Fold = 0), Tabellen ueber Kreuz (Spots ungerader Tage mit Tabellen gerader Tage und umgekehrt): CALL eines All-ins = Equity gegen die gezeigte Jam-Range des Knotens (Stufe, Tiefe; All-ins werden immer gezeigt) x Endtopf (Rake 5 %, Deckel 10 bb) - Nachlegen. JAM = P(alle folden | Knoten) x Topf jetzt + P(Call) x (Equity gegen die gezeigte Call-Range x Endtopf - Nachlegen). P(Fold) aus ALLEN Haenden mit einem Jam an diesem Knoten (Stufe, Tiefe, Zahl der Gegner, die noch handeln koennen), nicht nur aus Showdowns. CALL / RAISE ohne All-in: Nachflop-Spiel, nicht modellfrei bepreist (nur gezaehlt). spots [--prozesse 8] lauf [--arm K=V;...] [--prozesse 8] bericht [] Ausgaben mit Handnummern ausserhalb des Repos; ins Repo nur Summen. """ import collections import io import json import os import pickle import re import sys import zipfile import numpy as np _HIER = os.path.dirname(os.path.abspath(__file__)) _BAUM = os.path.dirname(os.path.dirname(_HIER)) sys.path.insert(0, _HIER) sys.path.insert(0, os.path.join(os.path.dirname(_HIER), "vorflop_population")) sys.path.insert(0, os.path.join(_BAUM, "werkzeuge")) import stackoff_linien as SL # noqa: E402 NL2 = 0.02 RANG = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", "8": "EIGHT", "7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"} FARBE = {"s": "SPADES", "h": "HEARTS", "d": "DIAMONDS", "c": "CLUBS"} RAKE, RAKE_DECKEL = 0.05, 10.0 GLATT = 30.0 TIEFEN = ["20-40", "40-80", ">=80"] RE_GEHOLT = re.compile(r"^(.+?) collected " + SL.B + r" from") ZEILEN = ["Open-Jam", "SB-Jam", "3-Bet-Jam", "4-Bet-Jam", "5-Bet+-Jam"] def tiefe(t): return None if t < 20 else 0 if t < 40 else 1 if t < 80 else 2 def jam_zeile(stufe, jammer_idx): """Raise Nummer `stufe` (1 = Open) als All-in -> Zeile wie VORFLOP_POP jamall.""" if stufe <= 1: return 1 if jammer_idx == 0 else 0 return min(stufe, 4) def karte_norm(c): return ("T" + c[2:]) if c.startswith("10") else c def wk(c): c = karte_norm(c) return {"rank": RANG[c[0].upper()], "suit": FARBE[c[-1].lower()]} def gruppe_von(nm, hf, gew): return "gew" if (SL.kenn(nm), 1 - hf) in gew else "feld" # ---------------------------------------------------------------- Hand -> Spots + Jam-Antworten def hand_spots(blk, gew, ich): z = [x.rstrip("\r") for x in blk.strip().splitlines()] m = SL.RE_KOPF.match(z[0]) if not m or abs(float(m.group(3)) - NL2) > 1e-9 or m.group(4): return None import calendar tag = calendar.timegm((int(m.group(5)), int(m.group(6)), int(m.group(7)), 0, 0, 0, 0, 0, 0)) // 86400 hf = tag % 2 knopf, sitze = None, {} for k in range(1, len(z)): mk = SL.RE_KNOPF.search(z[k]) if mk: knopf = int(mk.group(1)) ms = SL.RE_SITZ.match(z[k]) if ms: sitze[ms.group(2)] = (int(ms.group(1)), SL.zahl(ms.group(3))) elif z[k].startswith("*** HOLE CARDS"): break if knopf is None or len(sitze) < 2: return None aktiv, sb, bbn = set(), None, None for x in z[1:]: a = SL.RE_AKT.match(x) if a and a.group(1) in sitze: aktiv.add(a.group(1)) if a.group(2) == "posts small blind" and sb is None: sb = a.group(1) if a.group(2) == "posts big blind" and bbn is None: bbn = a.group(1) sitze = {nm: v for nm, v in sitze.items() if nm in aktiv} if sb is None or bbn is None or not 2 <= len(sitze) <= 6: return None nach = sorted(sitze, key=lambda nm: (sitze[nm][0] - knopf - 1) % 10) nach = nach[nach.index(sb):] + nach[:nach.index(sb)] n = len(nach) if nach[1 % n] != bbn and n > 2: return None pos = {nm: i for i, nm in enumerate(nach)} stacks = [sitze[nm][1] / NL2 for nm in nach] karten = {} for x in z[1:]: mz = SL.RE_ZEIGT.match(x) if mz and mz.group(1) in pos: karten[pos[mz.group(1)]] = [karte_norm(mz.group(2)), karte_norm(mz.group(3))] akt = [] # (i, art, ziel_bb, allin) ; art p (post), f, x, c, r for x in z[1:]: if x.startswith("*** FLOP") or x.startswith("*** SUMMARY") or x.startswith("*** SHOW"): break a = SL.RE_AKT.match(x) if not a or a.group(1) not in pos: continue i, was = pos[a.group(1)], a.group(2) allin = x.endswith("and is all-in") if was.startswith("posts"): akt.append((i, "p", SL.zahl(a.group(3)) / NL2, allin)) elif was == "folds": akt.append((i, "f", 0.0, False)) elif was == "checks": akt.append((i, "x", 0.0, False)) elif was == "calls": akt.append((i, "c", SL.zahl(a.group(3)) / NL2, allin)) elif was == "raises": akt.append((i, "r", SL.zahl(a.group(4)) / NL2, allin)) elif was == "bets": return None if sum(1 for a in akt if a[1] == "p") != 2: return None # Nachposten neuer Spieler: Lage nicht im Live-Format gruppen = [None if nm == ich else gruppe_von(nm, hf, gew) for nm in nach] # Geld der ganzen Hand: Einsatz je Spieler ueber alle Strassen (nach Rueckgabe) und Eingesammeltes einsatz, geholt, strasse = [0.0] * n, [0.0] * n, [0.0] * n for x in z[1:]: if x.startswith("*** SUMMARY"): break if x.startswith("*** FLOP") or x.startswith("*** TURN") or x.startswith("*** RIVER"): einsatz = [e + s_ for e, s_ in zip(einsatz, strasse)] strasse = [0.0] * n continue mr = SL.RE_ZURUECK.match(x) if mr and mr.group(2) in pos: strasse[pos[mr.group(2)]] -= SL.zahl(mr.group(1)) / NL2 continue mc = RE_GEHOLT.match(x) if mc and mc.group(1) in pos: geholt[pos[mc.group(1)]] += SL.zahl(mc.group(2)) / NL2 continue a = SL.RE_AKT.match(x) if not a or a.group(1) not in pos: continue i, was = pos[a.group(1)], a.group(2) if was == "raises": strasse[i] = SL.zahl(a.group(4)) / NL2 elif was in ("calls", "bets") or was.startswith("posts"): strasse[i] += SL.zahl(a.group(3)) / NL2 einsatz = [e + s_ for e, s_ in zip(einsatz, strasse)] knoten_ev = [] # (stufe, facing_allin, tiefe, aktion, gruppe, hf, netto_ab) jeder Entscheidung, gezeigt oder nicht beitrag = [0.0] * n hist = [] folded, allin_set = set(), set() hoch, stufe, inkr = 0.0, 0, 1.0 letzter, letzter_allin = None, False spots, jams = [], [] offen_jam = None # laufender Jam (zum Zaehlen der Antwort) for j, (i, art, betrag, allin) in enumerate(akt): rest = stacks[i] - beitrag[i] if art == "p": add = min(betrag, rest) beitrag[i] += add if add >= rest - 1e-9: allin_set.add(i) hoch = max(hoch, beitrag[i]) hist.append({"street": "PREFLOP", "seat": i + 1, "action": "POST_SB" if i == 0 and not hist else "POST_BB", "amount": round(beitrag[i] * NL2, 4)}) continue if i in folded or i in allin_set: continue tc = max(hoch - beitrag[i], 0.0) andere = [q for q in range(n) if q != i and q not in folded] eff_total = min(stacks[i], max((stacks[q] for q in andere), default=0.0)) # echte Aktion if art == "f": echt = "FOLD" elif art in ("x", "c"): echt = "CALL" else: echt = "JAM" if (allin or betrag >= 0.95 * stacks[i]) else "RAISE" call_allin = tc > 1e-9 and tc >= 0.9 * rest facing_allin = (letzter is not None and letzter_allin) or call_allin if echt == "CALL" and art == "c" and allin: call_allin = True netto_ab = geholt[i] - (einsatz[i] - beitrag[i]) if gruppen[i] is not None and tc > 1e-9 and stufe >= 1 and tiefe(eff_total) is not None: knoten_ev.append((min(stufe, 4), bool(facing_allin), tiefe(eff_total), echt, gruppen[i], hf, netto_ab, SL.klasse(karten[i]) if i in karten else None)) # offener Jam: diese Aktion ist eine Antwort darauf if offen_jam is not None and i != offen_jam["jammer"]: if art in ("c", "r"): offen_jam["gecallt"] = True if i in karten: offen_jam["caller"].append(SL.klasse(karten[i])) if (i in karten and gruppen[i] is not None and tc > 1e-9 and tiefe(eff_total) is not None and (stufe >= 2 or facing_allin or (stufe == 1 and echt in ("RAISE", "JAM")))) or ( i in karten and gruppen[i] is not None and stufe == 0 and echt == "JAM" and tiefe(eff_total) is not None): kann_raise = rest > tc + 1e-9 and any(q not in allin_set for q in andere) vil = [{"seat": q + 1, "stack": round(max(stacks[q] - beitrag[q], 0.0) * NL2, 4), "folded": q in folded} for q in range(n) if q != i] req = {"variant": "NLHE", "bigBlind": NL2, "seats": n, "heroSeat": i + 1, "buttonSeat": 1 if n == 2 else n, "heroCards": [wk(c) for c in karten[i]], "board": {}, "street": "PREFLOP", "pot": round(sum(beitrag) * NL2, 4), "toCall": round(min(tc, rest) * NL2, 4), "heroStack": round(rest * NL2, 4), "legalActions": ["FOLD", "CALL"] + (["RAISE"] if kann_raise else []), "allowedSizes": None, "villains": vil, "history": list(hist), "seed": (j * 7919 + n) & 0xFFFFFFFF} if kann_raise: req["minRaiseTo"] = round(min(hoch + max(inkr, 1.0), stacks[i]) * NL2, 4) req["maxRaiseTo"] = round(stacks[i] * NL2, 4) resp = [q for q in andere if q not in allin_set] # Endtopf, wenn der Spieler all-in callt: jeder Beitrag auf seinen Gesamtstack gedeckelt hero_total = stacks[i] topf_call = sum(min(b, hero_total) for q, b in enumerate(beitrag) if q != i) + min(hoch, hero_total) spots.append({ "req": req, "echt": echt, "gruppe": gruppen[i], "hf": hf, "klasse": SL.klasse(karten[i]), "stufe": stufe, "facing_allin": bool(facing_allin), "call_allin": bool(call_allin), "eff": eff_total, "tiefe": tiefe(eff_total), "idx": i, "n": n, "jam_zeile_gegen": jam_zeile(stufe, letzter) if (facing_allin and letzter is not None) else None, "jam_zeile_eigen": jam_zeile(stufe + 1, i), "n_resp": len(resp), "topf": sum(beitrag), "drin": beitrag[i], "tc": min(tc, rest), "hoch": hoch, "caller_drin": hoch if stufe >= 1 else 1.0, "topf_call": topf_call, "netto_ab": netto_ab, "hand": blk[len("CoinPoker Hand #"):].split(":")[0].strip()}) # Aktion anwenden if art == "f": folded.add(i) hist.append({"street": "PREFLOP", "seat": i + 1, "action": "FOLD"}) elif art == "x": hist.append({"street": "PREFLOP", "seat": i + 1, "action": "CHECK"}) elif art == "c": add = min(betrag, rest) beitrag[i] += add if allin or add >= rest - 1e-9: allin_set.add(i) hist.append({"street": "PREFLOP", "seat": i + 1, "action": "ALL_IN" if i in allin_set else "CALL", "amount": round(beitrag[i] * NL2, 4)}) else: ziel = min(betrag, stacks[i]) if ziel > hoch + 1e-9: stufe += 1 inkr = max(ziel - hoch, inkr) hoch = ziel letzter = i letzter_allin = allin or ziel >= stacks[i] - 1e-9 beitrag[i] = ziel if allin or ziel >= stacks[i] - 1e-9: allin_set.add(i) hist.append({"street": "PREFLOP", "seat": i + 1, "action": "ALL_IN" if i in allin_set else "RAISE", "amount": round(beitrag[i] * NL2, 4)}) if echt == "JAM" and tiefe(eff_total) is not None: if offen_jam is not None: jams.append(offen_jam) offen_jam = {"zeile": jam_zeile(stufe, i), "tiefe": tiefe(eff_total), "hf": hf, "n_resp": min(3, len([q for q in andere if q not in allin_set])), "jammer": i, "gecallt": False, "caller": []} if offen_jam is not None: jams.append(offen_jam) return spots, jams, knoten_ev def spots_teil(args): namen, zipf, gew, eigene, ich = args SL._bremse() za = zipfile.ZipFile(zipf) sp, jams, zaehl, kev = [], [], collections.Counter(), [] for name in namen: innen = zipfile.ZipFile(io.BytesIO(za.read(name))) for info in innen.infolist(): text = innen.read(info).decode("utf-8", "replace") for blk in re.split(r"\n\s*\n\s*\n", text): if not blk.strip().startswith("CoinPoker Hand #") or "straddle" in blk: continue nr = blk.strip()[len("CoinPoker Hand #"):].split(":")[0] if nr in eigene: continue try: r = hand_spots(blk, gew, ich) except (ValueError, IndexError, KeyError): zaehl["fehler"] += 1 r = None if r is None: continue zaehl["haende"] += 1 s, j, kv = r sp.extend(s) jams.extend(j) kev.extend(kv) return sp, jams, zaehl, kev def spots(args): import multiprocessing as mp zipf, gewf, eigf, ichf, aus = args[:5] k = int(args[args.index("--prozesse") + 1]) if "--prozesse" in args else 8 gew = pickle.load(open(gewf, "rb")) gew = gew["gew"] if isinstance(gew, dict) else gew eigene = set(open(eigf, encoding="utf-8").read().split()) ich = open(ichf, encoding="utf-8").read().strip() namen = sorted(i.filename for i in zipfile.ZipFile(zipf).infolist()) stuecke = [(namen[j::k], zipf, gew, eigene, ich) for j in range(k)] with mp.Pool(k) as p: res = p.map(spots_teil, stuecke) sp = [x for r in res for x in r[0]] jams = [x for r in res for x in r[1]] zaehl = sum((r[2] for r in res), collections.Counter()) kev = [x for r in res for x in r[3]] pickle.dump({"spots": sp, "jams": jams, "zaehl": zaehl, "knoten_ev": kev}, open(aus, "wb")) print("Haende", zaehl, "Spots", len(sp), "Jams", len(jams)) print(collections.Counter((s["stufe"], s["facing_allin"], s["echt"], s["gruppe"]) for s in sp).most_common(30)) # ---------------------------------------------------------------- Kern def kern_art(antwort, req): import kippliste as KL a = KL.art(antwort, req) if a == "ALL_IN": return "JAM" if a == "CALL" and float(req.get("toCall") or 0) >= 0.9 * float(req.get("heroStack") or 1e9): return "CALL" if a == "RAISE": gr = antwort.get("size") or antwort.get("amount") mx = req.get("maxRaiseTo") if gr is not None and mx and float(gr) >= 0.95 * float(mx): return "JAM" return "RAISE" if a == "CHECK": return "CALL" return a def lauf(args): import kippliste as KL spf, kern, schalter, aus = args[:4] pz = int(args[args.index("--prozesse") + 1]) if "--prozesse" in args else 8 arm = args[args.index("--arm") + 1] if "--arm" in args else "" d = pickle.load(open(spf, "rb")) env = KL.arm_env(KL.lies_schalter(schalter), arm) sp = d["spots"] antw = KL.kern_lauf(kern, [{"req": s["req"]} for s in sp], env, prozesse=pz) arten = [kern_art(a, s["req"]) for a, s in zip(antw, sp)] gruende = [(a.get("reason") or "")[:160] for a in antw] pickle.dump({"art": arten, "grund": gruende, "arm": arm}, open(aus, "wb")) print(collections.Counter(arten)) # ---------------------------------------------------------------- Preis class Preise: """Tabellen aus EINER Tageshaelfte: Jam-Ranges (gezeigte Jammer), Call-Ranges (gezeigte Caller), P(Fold), realisiertes Ergebnis ab der Entscheidung je Knoten und Aktion (alle Haende) und je Klasse (gezeigte Haende).""" def __init__(self, sp, jams, kev, hf, K): self.K = K J = np.zeros((5, 3, 169)) for s in sp: # gezeigte Jammer: ein Jam wird gezeigt, wenn er gecallt wird - unabhaengig von der eigenen Hand if s["hf"] == hf and s["echt"] == "JAM": J[s["jam_zeile_eigen"], s["tiefe"], K.id_von_name(s["klasse"])] += 1 C = np.zeros((5, 3, 169)) F = collections.Counter() for j in jams: if j["hf"] != hf: continue F[(j["zeile"], j["tiefe"], j["n_resp"], "n")] += 1 F[(j["zeile"], j["tiefe"], j["n_resp"], "c")] += j["gecallt"] F[(j["zeile"], j["tiefe"], "n")] += 1 F[(j["zeile"], j["tiefe"], "c")] += j["gecallt"] for kl in j["caller"]: C[j["zeile"], j["tiefe"], K.id_von_name(kl)] += 1 self.EJ = self._eq(J) self.EC = self._eq(C) self.F = F # realisiert ab der Entscheidung: je (stufe, facing_allin, tiefe, aktion) ueber alle Haende; gezeigt je Klasse self.R = collections.defaultdict(lambda: [0.0, 0]) self.RS = collections.defaultdict(lambda: [0.0, 0]) self.RK = collections.defaultdict(lambda: [0.0, 0]) for st, fa, t, a, g, h, net, kl in kev: if h != hf: continue for key, tab in (((st, fa, t, a), self.R),) + ((((st, fa, t, a), self.RS), ((st, fa, t, a, kl), self.RK)) if kl is not None else ()): r = tab[key] r[0] += net r[1] += 1 def _eq(self, C): E = np.zeros(C.shape) for z in range(5): alle = C[z].sum(axis=0) prior = alle / max(alle.sum(), 1) if alle.sum() == 0: prior = np.ones(169) / 169 for t in range(3): w = C[z, t] + GLATT * prior E[z, t] = self.K.E @ w / w.sum() return E def p_call(self, z, t, nr): n, c = self.F[(z, t, nr, "n")], self.F[(z, t, nr, "c")] n0, c0 = self.F[(z, t, "n")], self.F[(z, t, "c")] p0 = (c0 + 1) / (n0 + 2) return (c + 20 * p0) / (n + 20) def ev_real(self, s, aktion): """Realisiert ab der Entscheidung: Knotenmittel aller Haende + (Klassenmittel - Mittel) der gezeigten, geschrumpft mit n/(n+30). None, wenn der Knoten < 30 Faelle hat.""" key = (min(s["stufe"], 4), s["facing_allin"], s["tiefe"], aktion) sa, na = self.R[key] if key in self.R else (0.0, 0) if na < 30: return None m = sa / na ss, ns = self.RS[key] if key in self.RS else (0.0, 0) kk = key + (s["klasse"],) sk, nk = self.RK[kk] if kk in self.RK else (0.0, 0) if ns and nk: m += nk / (nk + 30.0) * (sk / nk - ss / ns) return m def ev(self, s, aktion, art="modell"): k = self.K.id_von_name(s["klasse"]) t = s["tiefe"] if aktion == "FOLD": return 0.0 if art == "real": return self.ev_real(s, aktion) if aktion == "CALL": if not (s["call_allin"] or s["facing_allin"]) or s["jam_zeile_gegen"] is None: return None if art == "nur_modell" else self.ev_real(s, aktion) eq = self.EJ[s["jam_zeile_gegen"], t, k] nach = min(s["hoch"], s["req"]["heroStack"] / NL2 + s["drin"]) - s["drin"] endtopf = s["topf_call"] rake = min(RAKE * endtopf, RAKE_DECKEL) return eq * (endtopf - rake) - nach if aktion == "JAM": if s["facing_allin"]: return self.ev(s, "CALL") z = s["jam_zeile_eigen"] pc = self.p_call(z, t, min(3, max(1, s["n_resp"]))) eq = self.EC[z, t, k] nach = s["eff"] - s["drin"] endtopf = s["topf"] + nach + max(s["eff"] - s["caller_drin"], 0.0) rake = min(RAKE * endtopf, RAKE_DECKEL) return (1 - pc) * s["topf"] + pc * (eq * (endtopf - rake) - nach) return None if art == "nur_modell" else self.ev_real(s, aktion) def knoten(s): if s["facing_allin"]: return "gegen %s" % ZEILEN[s["jam_zeile_gegen"]] if s["jam_zeile_gegen"] is not None else "gegen All-in ?" return {0: "Open-Jam-Wahl", 1: "gegen Open (3-Bet/Jam)", 2: "gegen 3-Bet", 3: "gegen 4-Bet"}.get(s["stufe"], "gegen 5-Bet+") def knoten_kev(st, fa): if fa: return "gegen All-in" return {1: "gegen Open (3-Bet/Jam)", 2: "gegen 3-Bet", 3: "gegen 4-Bet"}.get(st, "gegen 5-Bet+") PRAEMIE = {"AA", "KK", "QQ", "AKs", "AKo"} def bericht(args): import klassen as K spf, lf = args[0], args[1] armf = args[2] if len(args) > 3 else None aus = args[-1] d = pickle.load(open(spf, "rb")) sp, jams, kev = d["spots"], d["jams"], d["knoten_ev"] L = pickle.load(open(lf, "rb")) A = pickle.load(open(armf, "rb")) if armf else None P = {0: Preise(sp, jams, kev, 0, K), 1: Preise(sp, jams, kev, 1, K)} alle = collections.Counter() # alle Entscheidungen je (Knoten, Tiefe, echte Aktion, Gruppe), gezeigt oder nicht for st, fa, t, a, g, h, net, kl in kev: alle[(knoten_kev(st, fa), TIEFEN[t], a, g)] += 1 zellen = {} kl_abw = collections.Counter() for idx, s in enumerate(sp): pr = P[1 - s["hf"]] name = knoten(s) kn = "%s %s" % (name, TIEFEN[s["tiefe"]]) g = s["gruppe"] c = zellen.setdefault(kn, {"gew": collections.Counter(), "feld": collections.Counter()})[g] c["_kev"] = 0 echt, kern = s["echt"], L["art"][idx] c["n"] += 1 c["echt " + echt] += 1 c["kern " + kern] += 1 if echt != kern: c["abweichung"] += 1 c["%s->%s" % (echt, kern)] += 1 if kern == "FOLD": kl_abw[(name, s["klasse"], g)] += 1 for art in ("modell", "real"): ee, ek = pr.ev(s, echt, art), pr.ev(s, kern, art) if ee is None or ek is None: continue c["bepreist_" + art] += 1 c["kern_minus_echt_bb_" + art] += ek - ee c["echt_bb_" + art] += ee c["echt %s n_%s" % (echt, art)] += 1 if echt != kern: c["abw %s->%s n_%s" % (echt, kern, art)] += 1 c["abw %s->%s bb_%s" % (echt, kern, art)] += ek - ee if A is not None: ka = A["art"][idx] if ka != kern: c["arm_kipp"] += 1 c["arm %s->%s" % (kern, ka)] += 1 ea, ek = pr.ev(s, ka), pr.ev(s, kern) if ek is not None and ea is not None: c["arm_minus_kern_bb"] += ea - ek c["arm_kipp_bepreist"] += 1 if ka == "FOLD" and s["klasse"] in PRAEMIE: c["arm_praemie_neu_fold"] += 1 out = {} for kn, gg in sorted(zellen.items()): out[kn] = {} name, tf = kn.rsplit(" ", 1) name_a = "gegen All-in" if name.startswith("gegen ") and name.endswith("Jam") else name for g, c in gg.items(): if not c["n"]: continue c.pop("_kev", None) r = {k: (round(v, 2) if isinstance(v, float) else v) for k, v in sorted(c.items())} for art in ("modell", "real"): if c["bepreist_" + art]: r["kern_minus_echt_je_spot_" + art] = round(c["kern_minus_echt_bb_" + art] / c["bepreist_" + art], 3) # Hochrechnung: Mittel (kern - echt) je gezeigtem Spot einer echten Aktion x Zahl ALLER Entscheidungen # mit dieser Aktion am Knoten (gezeigt oder nicht). Gezeigte Calls sind staerker als alle Calls: grob. hoch = {} for a in ("CALL", "JAM", "RAISE"): n_a = c["echt %s n_modell" % a] bb_a = sum(v for k2, v in c.items() if k2.startswith("abw %s->" % a) and k2.endswith("bb_modell")) if n_a: hoch[a] = round(bb_a / n_a * alle[(name_a, tf, a, g)], 1) r["hochgerechnet_bb"] = hoch r["alle_entscheidungen"] = {a: alle[(name_a, tf, a, g)] for a in ("FOLD", "CALL", "JAM", "RAISE")} out[kn][g] = r top = collections.defaultdict(list) for (kn, kl, g), v in kl_abw.most_common(): if len(top[kn + " | " + g]) < 15: top[kn + " | " + g].append("%s %d" % (kl, v)) erg = {"spots": len(sp), "jams": len(jams), "entscheidungen": len(kev), "zaehl": dict(d["zaehl"]), "zellen": out, "kern_foldet_gezeigte_klassen": dict(top)} with open(aus, "w", encoding="utf-8", newline="\n") as f: json.dump(erg, f, ensure_ascii=False, indent=1) for kn, gg in out.items(): for g, r in gg.items(): print("%-30s %-4s n %6d abw %5d | modell %5d %+8.1f bb | real %5d %+8.1f bb | hoch %s | %s" % ( kn, g, r["n"], r.get("abweichung", 0), r.get("bepreist_modell", 0), r.get("kern_minus_echt_bb_modell", 0.0), r.get("bepreist_real", 0), r.get("kern_minus_echt_bb_real", 0.0), r["hochgerechnet_bb"], " ".join("%s:%d" % (k, v) for k, v in r.items() if "->" in k and " " not in k))) def feld(args): """Kern ueber alle 169 Klassen an Stichproben echter Spots je Knoten (beide Richtungen: auch dort, wo der echte Spieler foldete und nichts zeigte). Preis je Klasse wie oben; Bedauern = bestes bepreistes - Kern.""" import copy import random import kippliste as KL import klassen as K spf, kern, schalter, aus = args[:4] pz = int(args[args.index("--prozesse") + 1]) if "--prozesse" in args else 8 je = int(args[args.index("--je") + 1]) if "--je" in args else 120 arm = args[args.index("--arm") + 1] if "--arm" in args else "" d = pickle.load(open(spf, "rb")) sp, jams, kev = d["spots"], d["jams"], d["knoten_ev"] P = {0: Preise(sp, jams, kev, 0, K), 1: Preise(sp, jams, kev, 1, K)} nach_knoten = collections.defaultdict(list) for s in sp: if s["stufe"] >= 1 and s["tc"] > 0: nach_knoten["%s %s" % (knoten(s), TIEFEN[s["tiefe"]])].append(s) rnd = random.Random(1122) vorlagen = [] for kn, liste in sorted(nach_knoten.items()): vorlagen += [(kn, s) for s in rnd.sample(liste, min(je, len(liste)))] karten_je = {} R = "23456789TJQKA" for k in range(169): nm = K.name(k) a, b = nm[0], nm[1] karten_je[nm] = [a + "s", b + ("s" if nm.endswith("s") else "h")] if a != b else [a + "s", b + "h"] anfragen, meta = [], [] for kn, s in vorlagen: for nm, kc in karten_je.items(): r = copy.deepcopy(s["req"]) r["heroCards"] = [wk(c) for c in kc] anfragen.append({"req": r}) meta.append((kn, s, nm)) env = KL.arm_env(KL.lies_schalter(schalter), arm) antw = KL.kern_lauf(kern, anfragen, env, prozesse=pz) erg = collections.defaultdict(lambda: collections.Counter()) je_klasse = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.Counter())) for (kn, s, nm), a, q in zip(meta, antw, anfragen): ka = kern_art(a, q["req"]) s2 = dict(s, klasse=nm) pr = P[1 - s["hf"]] evs = {x: pr.ev(s2, x, "nur_modell") for x in ("FOLD", "CALL", "JAM")} ek = evs.get(ka) if ek is None: erg[kn]["kern_unbepreist"] += 1 continue best = max((v, x) for x, v in evs.items() if v is not None) w = 6 if nm[0] == nm[1] else 4 if nm.endswith("s") else 12 c = erg[kn] c["kombos"] += w c["bedauern_bb_x_kombos"] += w * (best[0] - ek) c["kern " + ka] += w c["bestes " + best[1]] += w if best[1] != ka: c["anders"] += w jk = je_klasse[kn][nm] jk["n"] += 1 jk["bedauern"] += best[0] - ek jk[ka + ">" + best[1]] += 1 out = {} for kn, c in sorted(erg.items()): r = dict(c) if c["kombos"]: r["bedauern_je_kombo_bb"] = round(c["bedauern_bb_x_kombos"] / c["kombos"], 3) teuer = sorted(((v["bedauern"] / v["n"], nm, max((kk for kk in v if ">" in kk), key=lambda kk: v[kk])) for nm, v in je_klasse[kn].items() if v["n"]), reverse=True)[:15] r["teuerste_klassen"] = ["%s %.2f bb (%s)" % (nm, b, x) for b, nm, x in teuer if b > 0.05] out[kn] = r print("%-30s Bedauern je Kombo %6.3f bb | %s" % (kn, r.get("bedauern_je_kombo_bb", 0.0), " ".join(r["teuerste_klassen"][:8]))) with open(aus, "w", encoding="utf-8", newline="\n") as f: json.dump({"vorlagen": len(vorlagen), "anfragen": len(anfragen), "arm": arm, "knoten": out}, f, ensure_ascii=False, indent=1) if __name__ == "__main__": {"spots": spots, "lauf": lauf, "bericht": bericht, "feld": feld}[sys.argv[1]](sys.argv[2:])