Files
pokerfreak/messung/eichung/tor/dritte.py
T

352 lines
17 KiB
Python

#!/usr/bin/env python3
"""River, dritte Wette (barrel3 BET): angenommene Gegnerantwort des Kerns gegen die tatsaechliche, auf genau den Spots.
Ein Kern mit Diagnose-Ausgabe (0d57fe60 + diag_annahme.patch) druckt je Einsatzgroesse seines Baums die gesperrte Antwort des
Gegners (Fold/Call/Raise aus seiner Range, Siegquote unserer Hand gegen seine Call-Range).
python -X utf8 dritte.py bauen <prozesse> alle barrel3-Einsaetze -> Anfragen (nicht gezeigte Hand: Zufallskarten, nur Blocker)
python -X utf8 dritte.py kern <prozesse> -> <AUS>/tor/dritte_kern.jsonl
python -X utf8 dritte.py bericht
python -X utf8 dritte.py sieg <prozesse> 0,30 gegen 0,43: Zusammensetzung gegen Call-Range, gleiche eigene Klasse
Daten mit Hand-Nummern bleiben ausserhalb des Repos."""
import sys
sys.dont_write_bytecode = True
import collections, io, json, math, os, random, re, subprocess, zipfile
from concurrent.futures import ThreadPoolExecutor
HIER = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HIER)
import fluss as FL # noqa: E402
import preis as PR # noqa: E402
SP, HS, hhd = FL.SP, FL.HS, FL.hhd
TOR = os.path.join(PR.AUS, "tor")
EXE = os.path.join(TOR, "pokerbench-eichung-diag.exe")
KARTEN = [r + s for r in "23456789TJQKA" for s in "cdhs"]
def bau_teil(args):
namen_z, ids, alle_gezeigten = args
HS._niedrig()
za = zipfile.ZipFile(HS.ZIP)
out = []
for name in namen_z:
innen = zipfile.ZipFile(io.BytesIO(za.read(name)))
for info in innen.infolist():
for blk in re.split(r"\n\s*\n\s*\n", innen.read(info).decode("utf-8", "replace")):
m = re.match(r"\s*CoinPoker Hand #(\d+)", blk)
if not m or m[1] not in ids:
continue
zeilen = [z.rstrip("\r") for z in blk.strip().splitlines()]
try:
r = HS.lesen(zeilen)
rr = hhd.hand_lesen(zeilen)
if not r or not rr:
continue
nr, tag, nach, hs = r
h = rr[0]
weg = {p for (st, p, a, z) in h["akt"] if st == 0 and a == "f"}
echt_gez = set(h["gezeigt"])
rng = random.Random(int(m[1]))
belegt = set(h["board"]) | {c for x in h["gezeigt"].values() for c in (x[:2], x[2:4])}
g2 = dict(h["gezeigt"])
for p in range(h["n"]):
if p not in weg and p not in g2:
c = rng.sample([k for k in KARTEN if k not in belegt], 2)
belegt |= set(c)
g2[p] = c[0] + c[1]
h = dict(h, gezeigt=g2)
for sp in SP.spots(h, dict(zip(nach, hs["netto"])), [True] * h["n"], True):
if sp["id"] in ids[m[1]]:
out.append({"id": sp["id"], "req": sp["req"], "gz": sp["req"]["heroSeat"] - 1 in echt_gez,
"held": sp["held"], "board": sp["board"][:5]})
except (ValueError, IndexError, KeyError):
pass
return out
def bauen(pr):
"""barrel3: alle Einsaetze; uebrige Linien: nur gecallte Einsaetze mit gezeigter Hand (fuer `sieg`)."""
import multiprocessing as mp
R = PR.lade_hhd()
ids = collections.defaultdict(set)
for d in R:
if d["a"] == "BET" and (d["li"] == "barrel3" or (d["zw"] == "c" and d["gz"])):
ids[d["id"].split(".")[0]].add(d["id"])
ids = dict(ids)
namen = sorted(i.filename for i in zipfile.ZipFile(HS.ZIP).infolist())
k = pr * 4
n = 0
with mp.Pool(pr, initializer=HS._niedrig) as pool, open(os.path.join(TOR, "dritte_spots.jsonl"), "w", encoding="utf-8") as f:
for z in pool.imap_unordered(bau_teil, [(namen[j::k], ids, None) for j in range(k)]):
for x in z:
f.write(json.dumps(x) + "\n")
n += 1
print(n, "Anfragen von", sum(map(len, ids.values())))
def umgebung(**kv):
t = subprocess.run(["git", "-C", HIER, "show", "0d57fe60:betrieb/kern_schalter.txt"], capture_output=True).stdout.decode()
e = dict(os.environ)
for z in t.splitlines():
z = z.split("#", 1)[0].strip()
if "=" in z:
k, v = z.split("=", 1)
e[k.strip()] = v.strip()
e.update(ANNAHME_DIAG="1", SOLVER_ZEIT="fest", SOLVER_ITER="hu_river:2", **kv)
return e
def annahme(req, env):
r = subprocess.run([EXE], input=json.dumps(req) + "\n", capture_output=True, text=True, encoding="utf-8", env=env,
creationflags=0x4000)
T = {}
for l in r.stderr.splitlines():
if l.startswith("ANNAHME "):
v = l.split()[1:]
T.setdefault(float(v[0]), [float(x) for x in v[1:6]] + [int(v[6])])
return sorted([k] + v for k, v in T.items())
def kern(pr):
env = umgebung()
R = {d["id"]: d for d in PR.lade_hhd()}
ziel = os.path.join(TOR, "dritte_kern.jsonl")
da = {json.loads(l)["id"] for l in open(ziel)} if os.path.exists(ziel) else set()
L = [x for x in map(json.loads, open(os.path.join(TOR, "dritte_spots.jsonl"))) if x["id"] not in da
and R[x["id"]]["li"] == "barrel3"]
with open(ziel, "a") as f, ThreadPoolExecutor(pr) as p:
for x, a in zip(L, p.map(lambda x: annahme(x["req"], env), L)):
f.write(json.dumps({"id": x["id"], "a": a}) + "\n")
def lies(a, r, allin):
"""Annahme bei Groesse r (Anteil Topf): All-in-Knoten, sonst linear zwischen den Baumgroessen -> f, c, r, Sieg|Call, Sieg."""
if not a:
return None
if allin:
z = [x for x in a if x[6]]
return z[0][1:6] if z else None
n = [x for x in a if not x[6]]
if not n:
return None
if r <= n[0][0]:
return n[0][1:6]
for u, v in zip(n, n[1:]):
if u[0] <= r <= v[0]:
t = (r - u[0]) / max(v[0] - u[0], 1e-9)
return [x + t * (y - x) for x, y in zip(u[1:6], v[1:6])]
return n[-1][1:6]
def wilson(k, n):
p = k / n
return 1.96 * math.sqrt(max(p * (1 - p), 1e-9) / n)
GR = {"k": "bis 0,45", "m": "0,45-0,85", "g": "0,85-1,3", "u": "ueber 1,3", "a": "All-in", "*": "alle"}
def bericht():
R = {d["id"]: d for d in PR.lade_hhd()}
S = {x["id"]: x for x in map(json.loads, open(os.path.join(TOR, "dritte_spots.jsonl"))) if R[x["id"]]["li"] == "barrel3"}
A = {x["id"]: x["a"] for x in map(json.loads, open(os.path.join(TOR, "dritte_kern.jsonl")))}
print("Anfragen", len(S), "Antworten", len(A), "ohne Annahme", sum(not a for a in A.values()))
pw = []
for g in ("gew", "feld"):
for f in ("k", "m", "g", "u", "a", "*"):
X = []
for i, s in S.items():
d = R[i]
if d["g"] != g or (f != "*" and d["fach"] != f) or d["zw"][0] not in "fcr":
continue
an = lies(A.get(i), d["b"] / d["topf"], d["fach"] == "a")
if an:
X.append((d, an))
n = len(X)
if n < 20:
continue
txt = ""
for j, (nm, w) in enumerate((("Fold", "f"), ("Call", "c"), ("Raise", "r"))):
k = sum(d["zw"][0] == w for d, _ in X)
e = sum(a[j] for _, a in X)
zz = (k - e) / math.sqrt(max(sum(a[j] * (1 - a[j]) for _, a in X), 1e-9))
txt += " %s %.3f/%.3f z%+.1f" % (nm, e / n, k / n, zz)
if f != "*":
pw.append((math.erfc(abs(zz) / math.sqrt(2)), g, f, nm))
C = [(d, a) for d, a in X if d["zw"] == "c"]
sh = [(d, a) for d, a in C if S[d["id"]]["gz"]]
if len(sh) >= 15:
k = sum(d["W"] for d, _ in sh)
e = sum(a[3] for _, a in sh)
zz = (k - e) / math.sqrt(max(sum(a[3] * (1 - a[3]) for _, a in sh), 1e-9))
txt += " | Sieg|Call n %d gezeigt %d: %.3f/%.3f +-%.3f z%+.1f (alle Calls %.3f)" % (
len(C), len(sh), e / len(sh), k / len(sh), wilson(k, len(sh)), zz, sum(d["W"] for d, _ in C) / len(C))
if f != "*":
pw.append((math.erfc(abs(zz) / math.sqrt(2)), g, f, "Sieg"))
print("%-4s %-9s n %5d" % (g, GR[f], n) + txt)
pw.sort()
nt = len(pw)
print("Tests", nt, "Bonferroni 5 %%: p < %.4f, auffaellig:" % (0.05 / nt), sum(p < 0.05 / nt for p, *_ in pw))
for p, *w in pw:
if p < 0.05 / nt:
print(" %.1e" % p, *w)
print("Siegquote bei Call je eigener Staerke (Annahme/echt, gezeigte, gew+feld)")
for a0, a1, nm in ((0, 3, "Luft k0-3"), (4, 6, "mittel k4-6"), (7, 7, "k7"), (8, 8, "k8"), (9, 9, "k9")):
sh = [(R[i], lies(A.get(i), R[i]["b"] / R[i]["topf"], R[i]["fach"] == "a")) for i in S
if S[i]["gz"] and R[i]["zw"] == "c" and a0 <= R[i]["k"] <= a1]
sh = [x for x in sh if x[1]]
if sh:
k = sum(d["W"] for d, _ in sh)
e = sum(a[3] for _, a in sh)
print(" %-12s n %5d Annahme %.3f echt %.3f +-%.3f" % (nm, len(sh), e / len(sh), k / len(sh), wilson(k, len(sh))))
# ------------------------------------------------------------------ 0,30 gegen 0,43
def pct(args):
"""stetiger Staerkerang am River (Anteil schlechterer Gegnerkombos + halbe Gleichstaende)."""
import itertools
i, held, board = args
E7 = FL.E7
b = E7.karten(list(board))
h = E7.karten(list(held))
me = E7.score7(h + b)
rest = [c for c in E7.VOLLDECK if c not in b and c not in h]
w = n = 0
for c in itertools.combinations(rest, 2):
s = E7.score7(list(c) + b)
n += 1
w += 1.0 if s < me else 0.5 if s == me else 0.0
return i, w / n
def lage_pct(args):
HS._niedrig()
return [pct(a) for a in args]
def eigene():
"""Eigene River-Einsaetze: Anfrage wie der Poolspot (ohne Reads), Karten aus karten.pkl."""
import pickle
sys.path.insert(0, os.path.join(HIER, ".."))
WV = dict(zip("TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING ACE".split(), "23456789TJQKA"))
WF = {"HEARTS": "h", "DIAMONDS": "d", "SPADES": "s", "CLUBS": "c"}
KA = pickle.load(open(os.path.join(PR.AUS, "karten.pkl"), "rb"))
U = {d["id"]: d for d in pickle.load(open(os.path.join(PR.AUS, "fluss_uns.pkl"), "rb")) if d["a"] == "BET"}
ich = open(HS.NAME, encoding="utf-8").read().strip()
nrs = {i.split(".")[0] for i in U}
out = []
for zeilen, blk in FL.ZE.blöcke(open(os.path.join(PR.AUS, "texte_eigen.txt"), encoding="utf8").read()):
r = HS.lesen(zeilen) if any(n in zeilen[0] for n in nrs) else None
if not r or str(r[0]) not in nrs:
continue
nr, tag, nach, hs = r
h = hhd.hand_lesen(zeilen)[0]
p_ich = h["namen"].index(ich)
ka = [c if isinstance(c, str) else WV[c["value"]] + WF[c["suit"]] for c in KA[str(nr)]]
g = dict(h["gezeigt"])
g[p_ich] = ka[0] + ka[1]
geg = {p: v for p, v in h["gezeigt"].items() if p != p_ich}
h = dict(h, gezeigt=g)
for sp in SP.spots(h, dict(zip(nach, hs["netto"])), [True] * h["n"], True):
if sp["id"] in U:
u = U.pop(sp["id"])
out.append(dict(u, req=sp["req"], held=ka, board=list(sp["board"])[:5], geg=list(geg.values())))
print("eigene River-Einsaetze", len(out), "ohne Anfrage", len(U))
return out
def sieg(pr):
import multiprocessing as mp
env = umgebung()
E = eigene()
R = {d["id"]: d for d in PR.lade_hhd()}
C = {x["id"]: x for x in map(json.loads, open(os.path.join(TOR, "dritte_spots.jsonl")))
if R[x["id"]]["zw"] == "c" and x["gz"]}
auf = [(i, x["held"], x["board"]) for i, x in C.items()] + [(d["id"], d["held"], d["board"]) for d in E]
with mp.Pool(pr) as pool:
P = dict(y for z in pool.imap_unordered(lage_pct, [auf[j::64] for j in range(64)]) for y in z)
with ThreadPoolExecutor(pr) as p:
AN = {d["id"]: a for d, a in zip(E, p.map(lambda d: annahme(d["req"], env), E))}
for d in E:
d["p"] = P[d["id"]]
d["an"] = lies(AN[d["id"]], d["b"] / d["topf"], d["fach"] == "a")
ok = [d for d in E if d["an"]]
print("eigene Einsaetze mit Annahme", len(ok), "von", len(E))
for nm, F in (("alle Linien", ok), ("barrel3", [d for d in ok if d["li"] == "barrel3"]),
("alle bis 19.11.", [d for d in ok if d["tag"] < 20779]), ("alle 22.11.", [d for d in ok if d["tag"] == 20779]),
("barrel3 22.11.", [d for d in ok if d["tag"] == 20779 and d["li"] == "barrel3"])):
n = len(F)
t = ""
for j, (a, w) in enumerate((("Fold", "f"), ("Call", "c"), ("Raise", "r"))):
e = sum(d["an"][j] for d in F)
k = sum(d["zw"][0] == w for d in F)
t += " %s %.3f/%.3f z%+.1f" % (a, e / n, k / n, (k - e) / math.sqrt(sum(d["an"][j] * (1 - d["an"][j]) for d in F)))
print(nm, n, "Annahme/echt", t)
POP = [(R[i], P[i]) for i in C]
KL = (("Luft k0-3", 0, .4), ("mittel k4-6", .4, .7), ("k7", .7, .8), ("k8", .8, .9), ("k9a 0,90-0,95", .9, .95), ("k9b 0,95+", .95, 1.01))
tests = 0
for lin, f in (("alle Linien", lambda d: True), ("barrel3", lambda d: d["li"] == "barrel3"), ("nicht barrel3", lambda d: d["li"] != "barrel3")):
U = [d for d in E if d["zw"] == "c" and f(d)]
print("==", lin, "eigene Calls", len(U), "gewonnen", sum(d["W"] for d in U), "mittlerer Rang %.3f" % (sum(d["p"] for d in U) / len(U)))
for g in ("gew", "feld", "beide"):
Q = [(d, p) for d, p in POP if (g == "beide" or d["g"] == g) and f(d)]
# gleiche Linie (wo moeglich gleiche Groesse), naechste 80 Haende im Rang
e = v = 0.0
zt = []
for d in U:
K = [(abs(p - d["p"]), x["W"]) for x, p in Q if x["li"] == d["li"] and x["fach"] == d["fach"]]
if len(K) < 200:
K = [(abs(p - d["p"]), x["W"]) for x, p in Q if x["li"] == d["li"]]
K.sort(key=lambda t: t[0])
K = K[:80]
q = sum(w for _, w in K) / len(K)
e += q
v += q * (1 - q)
zt.append((d, q))
k = sum(d["W"] for d in U)
tests += 1
zz = (k - e) / math.sqrt(v)
roh = sum(d["W"] for d, _ in Q) / len(Q)
luft = sum(p < .4 for _, p in Q) / len(Q)
print(" %-5s roh %.3f (Luft %.2f) -> mit unserer Zusammensetzung %.3f (unsere Luft %.2f) -> echt %.3f +-%.3f z%+.2f p%.3f" % (
g, roh, luft, e / len(U), sum(d["p"] < .4 for d in U) / len(U), k / len(U), wilson(k, len(U)), zz, math.erfc(abs(zz) / math.sqrt(2))))
if g != "gew":
for nm, a, b in KL:
z = [(d, q) for d, q in zt if a <= d["p"] < b]
if z:
tests += 1
print(" %-14s unser Anteil %.2f, Pool %.2f | n %2d erwartet %.2f echt %.2f" % (
nm, len(z) / len(U), sum(a <= p < b for _, p in Q) / len(Q), len(z), sum(q for _, q in z) / len(z), sum(d["W"] for d, _ in z) / len(z)))
z = [d for d in U if d["an"]]
e = sum(d["an"][3] for d in z)
v = sum(d["an"][3] * (1 - d["an"][3]) for d in z)
k = sum(d["W"] for d in z)
tests += 1
print(" Kern-Annahme (Pool ohne Reads) %.3f echt %.3f n %d z%+.2f" % (e / len(z), k / len(z), len(z), (k - e) / math.sqrt(v)))
ep = sorted({d["tag"] for d in U})
for nm, t in (("bis vorletzte Tage", lambda d: d["tag"] < ep[-1]), ("letzter Tag", lambda d: d["tag"] == ep[-1])):
y = [(d, q) for d, q in zt if t(d)]
if not y:
continue
n = len(y)
e = sum(q for _, q in y)
k = sum(d["W"] for d, _ in y)
ek = sum(d["an"][3] for d, _ in y)
zz = (k - e) / math.sqrt(sum(q * (1 - q) for _, q in y))
print(" %s (%s..%s) n %d Luft %.2f Rang %.2f | Pool bei gleicher Hand %.2f Kern %.2f echt %.2f +-%.2f z%+.2f p%.3f" % (
nm, min(d["tag"] for d, _ in y), max(d["tag"] for d, _ in y), n, sum(d["p"] < .4 for d, _ in y) / n,
sum(d["p"] for d, _ in y) / n, e / n, ek / n, k / n, wilson(k, n), zz, math.erfc(abs(zz) / math.sqrt(2))))
tests += 1
# alle Werte-Klassen ohne Luft: hier trennt sich Zusammensetzung von Call-Range
y = [(d, q) for d, q in zt if d["p"] >= .4]
e = sum(q for _, q in y); k = sum(d["W"] for d, _ in y)
print(" ohne Luft n %d erwartet %.2f echt %.2f z%+.2f" % (len(y), e / len(y), k / len(y), (k - e) / math.sqrt(sum(q * (1 - q) for _, q in y))))
tests += 1
print("Tests", tests)
print("Rang des gezeigten Gegners in verlorenen/gewonnenen Calls: gezeigt", sum(bool(d["geg"]) for d in E if d["zw"] == "c"))
if __name__ == "__main__":
k = sys.argv[1]
if k == "bericht":
bericht()
elif k in ("bauen", "kern", "sieg"):
globals()[k](int(sys.argv[2]))