Files
pokerfreak/messung/bluff/reg_raise.py
T

235 lines
10 KiB
Python

#!/usr/bin/env python3
"""Gewinnende Regs in vier Lagen: Netto (bb, ganze Hand) wenn sie raisen gegen wenn sie callen, je Handklasse und
Raise-Groesse, nur echte Ergebnisse (hhDealer NL2 bis 16.11., ohne eigene Haende).
Lagen (erste Antwort des Regs auf einen Einsatz der Strasse, noch ohne eigenen Einsatz/Raise auf ihr):
L1 Flop heads-up, OOP, Vorflop-Caller, hat gecheckt -> Raise = Check-Raise
L2 Flop heads-up, IP, Vorflop-Caller
L3 Turn heads-up, IP, Vorflop-Aggressor
L4 River Mehrweg (>= 3 aktiv), hat gecheckt -> Raise = Check-Raise
Groesse: Ziel / Topf nach Call (< 0,6 | >= 0,6 ohne All-in); All-in nach s = effektiver Zusatz / Topf davor
(<1, 1-2, 2-4, >4). Dev streng: Reg und Setzer nicht versiegelt (blake2b-8("CP|name") unsigned % 10 < 3).
Zwei Sichten:
alle Netto aller Spots je Aktion, ohne Klasse (keine Showdown-Auswahl, aber Handmischung verschieden)
Klasse nur Haende, in denen der Reg seine Karten zeigt (Showdown) -> Klasse am Brett der Lage. Starke Auswahl:
Raises, die sofort Folds holen, fehlen; Netto ist Netto unter der Bedingung Showdown.
python -I -X utf8 messung/bluff/reg_raise.py <aussen.zip> <eigene_ids.txt> <eigener_name.txt> <regulars.npz> <aus.json>
[--prozesse 4]
"""
import collections
import io
import json
import os
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))
for _p in (_hier, os.path.join(_baum, "lesen", "eigene_wetten"), os.path.join(_baum, "lesen")):
sys.path.insert(0, _p)
from scan import (RE_AKT, RE_BRETT, RE_SAMMELT, RE_ZEIGT, RE_ZURUECK, STICHTAG, hand_lesen, kennung, # noqa: E402
zahl)
from poolruf_eichung import klasse, KLASSEN # noqa: E402
from fold_scan import _idle, versiegelt # noqa: E402
REGS = None
def groesse(ziel, plus, stapel_nm, topf_vor, hoch, bv, rest_max):
allin = plus >= stapel_nm - 1e-9 or ziel >= rest_max - 1e-9
if allin:
a_eff = min(plus, rest_max - bv)
s = a_eff / max(topf_vor, 1e-9)
return "all-in <1" if s < 1 else "all-in 1-2" if s < 2 else "all-in 2-4" if s < 4 else "all-in >4"
r = ziel / max(topf_vor + hoch - bv, 1e-9)
return "<0,6" if r < 0.6 else ">=0,6"
def hand(zeilen, kopf, st, out):
nr, bb, zeit, nach, pos, sitze = kopf
stapel = {nm: sitze[nm][1] for nm in nach}
inv = collections.Counter()
beitrag = collections.Counter()
gezeigt = {}
gesammelt = collections.Counter()
zurueck = collections.Counter()
s = 0
aktiv = set(nach)
pfa = None
brett = {}
b = []
gecheckt = collections.defaultdict(set)
gesetzt = collections.defaultdict(set)
setzer = {}
kand = []
folge = []
erh = 0
for z in zeilen[1:]:
if z.startswith("*** FLOP"):
s = 1; beitrag = collections.Counter(); b = RE_BRETT.findall(z)[0].split(); brett[1] = list(b); continue
if z.startswith("*** TURN"):
s = 2; beitrag = collections.Counter(); b = b[:3] + RE_BRETT.findall(z)[-1].split(); brett[2] = list(b)
continue
if z.startswith("*** RIVER"):
s = 3; beitrag = collections.Counter(); b = b[:4] + RE_BRETT.findall(z)[-1].split(); brett[3] = list(b)
continue
if z.startswith("*** SUMMARY"):
break
mz = RE_ZEIGT.match(z)
if mz and mz.group(1) in pos:
gezeigt[mz.group(1)] = [mz.group(2), mz.group(3)]; continue
mc = RE_SAMMELT.match(z)
if mc and mc.group(1) in pos:
gesammelt[mc.group(1)] += zahl(mc.group(2)); continue
mr = RE_ZURUECK.match(z)
if mr and mr.group(2) in pos:
zurueck[mr.group(2)] += zahl(mr.group(1)); continue
a = RE_AKT.match(z)
if not a or a.group(1) not in pos:
continue
nm, was = a.group(1), a.group(2)
b1, b2 = zahl(a.group(3)), zahl(a.group(4))
if was == "posts the ante":
inv[nm] += b1; stapel[nm] -= b1; continue
if was.startswith("posts"):
beitrag[nm] += b1; inv[nm] += b1; stapel[nm] -= b1; continue
bv = beitrag[nm]
hoch = max(beitrag.values() or [0])
topf_vor = sum(inv.values())
if (s >= 1 and hoch > bv + 1e-9 and nm not in gesetzt[s] and was in ("raises", "calls", "folds")
and kennung(nm) in REGS):
n_akt = len(aktiv)
ordn = sorted(aktiv, key=lambda x: pos[x])
ip = ordn[-1] == nm
caller = pfa is not None and pfa != nm
lage = None
if s == 1 and n_akt == 2 and not ip and caller and nm in gecheckt[1]:
lage = "L1 Flop-CR HU OOP-Caller"
elif s == 1 and n_akt == 2 and ip and caller:
lage = "L2 Flop-Raise HU IP-Caller"
elif s == 2 and n_akt == 2 and ip and pfa == nm:
lage = "L3 Turn-Raise HU IP-PFA"
elif s == 3 and n_akt >= 3 and nm in gecheckt[3]:
lage = "L4 River-CR Mehrweg"
if lage and not versiegelt(kennung(nm)) and not versiegelt(kennung(setzer.get(s, nm))):
gr = None
if was == "raises":
rest_max = max(stapel[p] + beitrag[p] for p in aktiv if p != nm)
gr = groesse(b2, b2 - bv, stapel[nm], topf_vor, hoch, bv, rest_max)
kand.append((nm, lage, {"raises": "raise", "calls": "call", "folds": "fold"}[was], gr, s, len(folge)))
folge.append((s, nm, was))
if was == "folds":
aktiv.discard(nm); continue
if was == "checks":
if s >= 1:
gecheckt[s].add(nm)
continue
if was == "calls":
ziel = bv + b1
elif was == "bets":
ziel = bv + b1
setzer[s] = nm
if s >= 1:
gesetzt[s].add(nm)
else:
ziel = b2
if s == 0:
pfa = nm; erh += 1
else:
gesetzt[s].add(nm); setzer[s] = nm
plus = ziel - bv
beitrag[nm] = ziel; inv[nm] += plus; stapel[nm] -= plus
for nm, lage, akt, gr, s_, i0 in kand:
netto = (gesammelt[nm] + zurueck[nm] - inv[nm]) / bb
kl = KLASSEN[klasse(gezeigt[nm], brett[s_])] if nm in gezeigt and s_ in brett else None
# Ausgang: 1 Gegner foldet sofort, 2 Reraise und Reg foldet, 3 weiter bis Showdown mit gezeigten Karten,
# 4 weiter ohne gezeigte Karten (spaeter Fold oder Muck); Fold-Spots 0
ausgang = 0
if akt != "fold":
ausgang = 3 if nm in gezeigt else 4
if akt == "raise":
rest = [e for e in folge[i0 + 1:] if e[0] == s_]
erst = next((e for e in rest if e[1] != nm), None)
if erst and erst[2] == "folds" and lage[:2] != "L4":
ausgang = 1
elif erst and erst[2] == "raises":
nach = next((e for e in rest[rest.index(erst) + 1:] if e[1] == nm), None)
if nach and nach[2] == "folds":
ausgang = 2
out.append((lage, akt, gr, kl, netto, ausgang, kennung(nm), min(erh, 3)))
st["spots"] += 1
def _teil(args):
global REGS
aussen, namen, ids_pfad, name_pfad, regs_pfad, k = args
_idle()
REGS = set(np.load(regs_pfad)["regulars"].tolist())
eigene = set(open(ids_pfad, encoding="utf-8").read().split())
ich = {x.strip() for x in open(name_pfad, encoding="utf-8").read().splitlines() if x.strip()}
za = zipfile.ZipFile(aussen)
st = collections.Counter()
out = []
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):
zeilen = [z.rstrip("\r") for z in blk.strip().splitlines()]
if not zeilen or not zeilen[0].startswith("CoinPoker Hand #"):
continue
try:
kopf = hand_lesen(zeilen)
except (ValueError, IndexError, KeyError):
kopf = None
if not kopf or kopf[0] in eigene or (ich & set(kopf[5])) or kopf[2] >= STICHTAG:
continue
st["haende"] += 1
try:
hand(zeilen, kopf, st, out)
except (ValueError, IndexError, KeyError, ZeroDivisionError):
st["fehler"] += 1
agg = collections.defaultdict(lambda: [0, 0.0, 0.0])
for lage, akt, gr, kl, netto, _, _, _ in out:
keys = [(lage, akt, gr or "-", "alle"), (lage, akt, "*", "alle")]
if kl:
keys += [(lage, akt, gr or "-", kl), (lage, akt, "*", kl)]
for kk in keys:
x = agg[kk]; x[0] += 1; x[1] += netto; x[2] += netto * netto
return k, dict(st), {"|".join(kk): v for kk, v in agg.items()}, out
def main(a):
aussen, ids, name, regs, aus = a[:5]
proz = int(a[a.index("--prozesse") + 1]) if "--prozesse" in a else 4
import multiprocessing as mp
namen = sorted(i.filename for i in zipfile.ZipFile(aussen).infolist())
if os.environ.get("BLUFF_PROBE"):
namen = namen[1:1 + int(os.environ["BLUFF_PROBE"])]
k = max(min(proz * 6, len(namen)), 1)
ges = collections.Counter()
A = collections.defaultdict(lambda: [0, 0.0, 0.0])
Z = []
with mp.Pool(proz, initializer=_idle) as pool:
for kz, st, agg, rows in pool.imap_unordered(_teil, [(aussen, namen[i::k], ids, name, regs, i) for i in range(k)]):
ges.update(st)
for kk, v in agg.items():
x = A[kk]; x[0] += v[0]; x[1] += v[1]; x[2] += v[2]
Z.extend(rows)
print("Teil %d fertig; %s" % (kz, dict(ges)), flush=True)
json.dump({"zaehler": dict(ges), "agg": A}, open(aus, "w", encoding="utf-8"))
# Einzelzeilen (ohne Namen; Kennung = Hash) fuer Bootstrap ueber Spieler
with open(aus + ".zeilen.jsonl", "w", encoding="utf-8", newline="\n") as f:
for r in Z:
f.write(json.dumps(r, separators=(",", ":")) + "\n")
print("fertig", dict(ges), flush=True)
if __name__ == "__main__":
main(sys.argv[1:])