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

289 lines
13 KiB
Python

#!/usr/bin/env python3
"""Pfadpreis-Tor, Schritt 1: River-Scan ueber ALLE hhDealer-Haende (HU-Flop-Toepfe, 3-6 Sitze, wie die Gewinnerspots).
Je River-Entscheidung (ohne offenen Einsatz, oder gegen Einsatz) eines Gewinners (cross-fit) oder Feldspielers
(Hand-Nr. % 40 == 0) ein Datensatz, gezeigt oder nicht:
id "nr.i" (wie gewinnerspots/spots), g gew|feld, li Linie, ip, pa limp|sr|3b|4b, a BET|CHECK|CALL|FOLD|RAISE,
fach (Groesse des eigenen Einsatzes bzw. des Einsatzes gegen uns), topf, tc, b (eigener Einsatz, bb), G (ab hier, bb),
zw Zweig nach der Entscheidung, W (Netto > 0), gz (Hand am Ende gezeigt), k (Staerke-Zehntel, nur wenn gezeigt).
Zweige: BET -> f | c | r<f/c/r> ; CHECK -> sd (Showdown) | x (Gegner checkt, Showdown) | b<fach><f/c/r> ;
CALL -> sd ; FOLD -> - ; RAISE -> f | c | r
k: Rang der Heldenhand am River unter allen 990 Gegnerkombos (Anteil schlechter + halbe Gleichstaende), Zehntel 0..9.
python -I -X utf8 fluss.py hhd <prozesse> -> <AUS>/fluss_hhd.pkl (Liste von Datensaetzen)
python -I -X utf8 fluss.py uns <texte> <karten.pkl> -> <AUS>/fluss_uns.pkl (eigene Haende, alle mit k)
Daten bleiben ausserhalb des Repos (Hand-Nummern, keine Namen)."""
import sys
sys.dont_write_bytecode = True
import collections, io, itertools, os, pickle, re, zipfile
HIER = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HIER, ".."))
sys.path.insert(0, os.path.join(HIER, "..", "..", "..", "entscheiden"))
import zellen as ZE # noqa: E402 (HS = hhd_scan, AUS)
import eval7 as E7 # noqa: E402
GS = os.path.join(os.path.expanduser("~"), "pokerfreak-regulars", "gewinnerspots")
sys.path.insert(0, GS)
import spots as SP # noqa: E402 (linie, hhd, HS)
HS = SP.HS
hhd = SP.hhd
AUS = ZE.AUS
def fach(r):
return "k" if r < 0.45 else "m" if r < 0.85 else "g" if r < 1.3 else "u"
def staerke(held, board):
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]
schlechter = gleich = 0
n = 0
for c in itertools.combinations(rest, 2):
s = E7.score7(list(c) + b)
n += 1
if s < me:
schlechter += 1
elif s == me:
gleich += 1
return min(int(10 * (schlechter + 0.5 * gleich) / n), 9)
def datensaetze(h, netto, entsch, gew_flag, karten_von, s_ziel=3):
"""Entscheidungen auf Strasse s_ziel (3 River, 2 Turn) der Spieler in entsch. karten_von(p) -> Karten oder None.
Turn- und Flop-Datensaetze tragen zusaetzlich: hk (Karten, wenn gezeigt), brett (Board bis zum Ende), kr (Staerke
am River mit dem echten Board), kt (Staerke am Turn, gemachte Hand), rn (erster Knoten des Spielers auf der
naechsten Strasse: ("nb", Linie) ohne Einsatz, ("vs", Groesse) gegen Einsatz, ("ende",) wenn er dort nicht mehr
entscheidet)."""
n = h["n"]
weg_vf = {p for (st, p, a, z) in h["akt"] if st == 0 and a == "f"}
leb = [q for q in range(n) if q not in weg_vf]
if len(leb) != 2 or h["strassen"] < s_ziel or len(h["board"]) < s_ziel + 2:
return []
rn = {}
namen = h["namen"]
beitrag = list(h["blinds"])
gesamt = list(h["blinds"])
stack = [st - b for st, b in zip(h["stacks"], h["blinds"])]
topf_vor = 0.0
s = 0
aggr = {}
pfa = None
raises = 0
check_str = set()
aggr_vor = {}
r_str = 0 # Einsaetze/Raises auf dieser Strasse bisher
def oop_fehlt(p, o):
"""Held IP: kein Check des OOP-Gegners vor dessen Einsatz; Held OOP: hat selbst gecheckt."""
return p < o
akt = h["akt"]
out = []
for i, (st, p, art, ziel) in enumerate(akt):
if st != s:
topf_vor += sum(beitrag)
beitrag = [0.0] * n
s = st
check_str = set()
aggr_vor = dict(aggr)
r_str = 0
hoch = max(beitrag)
tc = max(hoch - beitrag[p], 0.0)
if s_ziel < 3 and s == s_ziel + 1 and p in leb and p not in rn and stack[p] > 1e-9:
o = [q for q in leb if q != p][0]
t3 = topf_vor + sum(beitrag)
rn[p] = ("vs", fach(tc / max(t3 - tc, 1e-9))) if tc > 1e-9 else ("nb", SP.linie(s, p, o, pfa, aggr, hoch, o in check_str))
if s == s_ziel and p in leb and p in entsch and stack[p] > 1e-9 and namen[p] in netto:
o = [q for q in leb if q != p][0]
offen = tc <= 1e-9 and stack[o] > 1e-9
if offen or tc > 1e-9:
li = SP.linie(s, p, o, pfa, aggr, hoch, o in check_str)
topf = topf_vor + sum(beitrag)
bb = h["bb"]
G = netto[namen[p]] + gesamt[p] / bb
b = 0.0
if offen:
if art == "r":
b = min(ziel - beitrag[p], stack[p])
allin = b >= stack[p] - 1e-9
a, fa = "BET", ("a" if allin else fach(b / max(topf, 1e-9)))
else:
a, fa = "CHECK", "-"
else:
a = "FOLD" if art == "f" else "CALL" if art == "c" else "RAISE"
fa = fach(tc / max(topf - tc, 1e-9))
if art == "r":
b = min(ziel - beitrag[p], stack[p])
elif art == "c":
b = min(tc, stack[p])
# Zweig
nach = [(p2, a2, z2) for (st2, p2, a2, z2) in akt[i + 1:] if st2 == s_ziel]
if art == "f":
zw = "-"
elif not nach:
zw = "sd"
else:
p2, a2, z2 = nach[0]
if a2 == "f":
zw = "f"
elif a2 == "c":
zw = "c" if art == "r" else "x"
else:
# Gegner setzt/erhoeht; Groesse relativ zum Topf vor seinem Einsatz
t2 = topf + (b if art in ("r", "c") else 0.0)
hoch2 = max(z2 - (b if art == "r" else 0.0), 0.0)
f2 = fach(hoch2 / max(t2, 1e-9))
r3 = next((a3 for (p3, a3, z3) in nach[1:] if p3 == p), None)
zw = ("r" if art == "r" else "b") + f2 + {"f": "f", "c": "c", "r": "r", None: "-"}[r3]
gz = karten_von(p)
if s_ziel == 3:
k = staerke(gz, h["board"][:5]) if gz else None
else:
k = None
out.append({"id": "%d.%d" % (h["nr"], i), "g": "gew" if gew_flag[p] else "feld", "li": li, "ip": p > o,
"pa": ["limp", "sr", "3b", "4b"][min(raises, 3)], "a": a, "fach": fa,
"topf": topf / bb, "tc": min(tc, stack[p]) / bb, "b": b / bb, "G": G,
"zw": zw, "W": netto[namen[p]] > 0, "gz": bool(gz), "k": k,
"stack": stack[p] / bb, "stack_o": stack[o] / bb, "_p": p,
# n7: Linie vor dem Einsatz des Gegners, investiert vor der Entscheidung, Plaetze, Karten
"li0": SP.linie(s, p, o, pfa, aggr_vor, 0.0, (not oop_fehlt(p, o))) if tc > 1e-9 else li,
"inv": gesamt[p] / bb, "p": p, "j": i, "hk": gz, "brett": list(h["board"][:5]),
"r_vor": r_str})
if s_ziel < 3:
out[-1].update({"kf": staerke(gz, h["board"][:3]) if gz and s_ziel == 1 else None,
"kr": staerke(gz, h["board"][:5]) if gz and len(h["board"]) >= 5 else None,
"kt": staerke(gz, h["board"][:4]) if gz and len(h["board"]) >= 4 else None})
if art == "c":
if tc > 1e-9:
add = min(tc, stack[p])
beitrag[p] += add; gesamt[p] += add; stack[p] -= add
else:
check_str.add(p)
elif art == "r":
add = min(ziel - beitrag[p], stack[p])
beitrag[p] += add; gesamt[p] += add; stack[p] -= add
aggr[s] = p
r_str += 1
if s == 0:
pfa = p
raises += 1
for d in out:
p = d.pop("_p")
if s_ziel < 3:
d["rn"] = rn.get(p, ("ende",))
return out
def teil(args):
namen_z, gew, modulo, kz, s_ziel = args
marke = {3: "*** RIVER", 2: "*** TURN", 1: "*** FLOP"}[s_ziel]
HS._niedrig()
eigene = set(open(HS.EIGENE, encoding="utf-8").read().split())
ich = open(HS.NAME, encoding="utf-8").read().strip()
za = zipfile.ZipFile(HS.ZIP)
out = []
for name in namen_z:
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 #") or "straddle" in blk or "Ante" in zeilen[0]:
continue
if marke not in blk:
continue
try:
r = HS.lesen(zeilen)
if not r:
continue
nr, tag, nach, hs = r
m = HS.RE_RAKE.search(blk)
rake = HS.zahl(m.group(1)) / 0.02 if m else 0.0
if nr in eigene or ich in nach or hs["n"] < 3 or abs(sum(hs["netto"]) + rake) >= 0.6:
continue
rr = hhd.hand_lesen(zeilen)
if not rr:
continue
h = rr[0]
if abs(h["bb"] - 0.02) > 1e-9 or h["n"] > 6 or h["n"] < 3:
continue
ks = [HS.kenn(nm) for nm in h["namen"]]
gf = [(k, 1 - tag % 2) in gew for k in ks]
feld = int(nr) % modulo == 0
entsch = {p for p in range(h["n"]) if gf[p] or feld}
if not entsch:
continue
gez = h["gezeigt"]
kv = (lambda p: [gez[p][0:2], gez[p][2:4]] if p in gez else None)
out.extend(datensaetze(h, dict(zip(nach, hs["netto"])), entsch, gf, kv, s_ziel))
except (ValueError, IndexError, KeyError):
pass
return out
def main_hhd(pr, s_ziel=3):
import multiprocessing as mp
HS._niedrig()
gew = pickle.load(open(os.path.join(os.path.expanduser("~"), "pokerfreak-regulars", "echtgewinner", "gewinner.pkl"), "rb"))["gew"]
namen = sorted(i.filename for i in zipfile.ZipFile(HS.ZIP).infolist())
k = pr * 4
alle = []
with mp.Pool(pr, initializer=HS._niedrig) as pool:
for j, z in enumerate(pool.imap_unordered(teil, [(namen[i::k], gew, 40, i, s_ziel) for i in range(k)])):
alle.extend(z)
print("fluss %d/%d %d" % (j + 1, k, len(alle)), flush=True)
pickle.dump(alle, open(os.path.join(AUS, "n7_hhd_s%d.pkl" % s_ziel if os.environ.get("N7") else "fluss_hhd.pkl" if s_ziel == 3 else "fluss_hhd_s%d.pkl" % s_ziel), "wb"))
def main_uns(texte, karten_pkl, s_ziel=3):
"""Eigene Haende: Entscheider = ich, Karten aus karten.pkl (Hand-Nr. -> zwei Karten)."""
WV = {"TWO": "2", "THREE": "3", "FOUR": "4", "FIVE": "5", "SIX": "6", "SEVEN": "7", "EIGHT": "8", "NINE": "9",
"TEN": "T", "JACK": "J", "QUEEN": "Q", "KING": "K", "ACE": "A"}
WF = {"HEARTS": "h", "DIAMONDS": "d", "SPADES": "s", "CLUBS": "c"}
karte = (lambda c: c if isinstance(c, str) else WV[c["value"]] + WF[c["suit"]])
ich = open(HS.NAME, encoding="utf-8").read().strip()
KA = pickle.load(open(karten_pkl, "rb"))
text = open(texte, encoding="utf8").read()
out = []
for zeilen, blk in ZE.blöcke(text):
if {3: "*** RIVER", 2: "*** TURN", 1: "*** FLOP"}[s_ziel] not in blk:
continue
try:
r = HS.lesen(zeilen)
if not r:
continue
nr, tag, nach, hs = r
if ich not in nach:
continue
rr = hhd.hand_lesen(zeilen)
if not rr:
continue
h = rr[0]
if h["n"] > 6:
continue
ka = KA.get(str(nr))
if not ka or len(ka) != 2:
continue
ka = [karte(c) for c in ka]
p_ich = h["namen"].index(ich) if ich in h["namen"] else None
if p_ich is None:
continue
gf = [False] * h["n"]
ds = datensaetze(h, dict(zip(nach, hs["netto"])), {p_ich}, gf, lambda p: ka if p == p_ich else None, s_ziel)
for d in ds:
d["g"] = "uns"
d["tag"] = tag
out.extend(ds)
except (ValueError, IndexError, KeyError):
pass
pickle.dump(out, open(os.path.join(AUS, "n7_uns_s%d.pkl" % s_ziel if os.environ.get("N7") else "fluss_uns.pkl" if s_ziel == 3 else "fluss_uns_s%d.pkl" % s_ziel), "wb"))
print(len(out), "eigene Entscheidungen, Strasse", s_ziel)
if __name__ == "__main__":
# python fluss.py hhd <prozesse> [strasse 3|2]; python fluss.py uns <texte> <karten.pkl> [strasse]
if sys.argv[1] == "hhd":
main_hhd(int(sys.argv[2]), int(sys.argv[3]) if len(sys.argv) > 3 else 3)
else:
main_uns(sys.argv[2], sys.argv[3], int(sys.argv[4]) if len(sys.argv) > 4 else 3)