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

297 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Pfadpreis-Tor fuer River-Entscheidungen ohne Einsatz vor uns (heads-up, hhDealer NL2 6-max), zwei Arme.
python -I -X utf8 tor.py spots Anfragen fuer alle gewichteten Spots bauen (einmal)
python -I -X utf8 tor.py arm <marke> [--bin EXE] [--schalter DATEI] [--setze K=V]... [--ohne K]... [--prozesse 8]
Kern auf allen Spots fragen (wiederaufnehmbar)
python -I -X utf8 tor.py vergleich <A> <B> [--teil a|b|alle]
bb/100 A minus B je Gruppe (Feld, Gewinner), je Linie, mit SE;
Nullprobe laeuft immer mit und muss 0 +-2 bb/100 sein
python -I -X utf8 tor.py eichung [--teil alle] Eichtor: Preis unserer echten River-Entscheidungen gegen echt
Preis und Gewichte: preis.py (Pfadpreis ueber ALLE Haende des Knotens, Karten nur ueber den offenlegenden Zweig mit
Verlierer-IPW). Ankunft: beide Arme teilen die Ankunft am River (der Schalter wirkt nur am River), die Gewichte bilden
die Ankunft der Population je Knoten, Topfstufe und Handstaerke ab. Teil a/b: Hand-Nr. nach md5 halbiert; die Tafeln
kommen dann aus der anderen Haelfte (Kreuzanpassung).
Daten ausserhalb des Repos unter <AUS>/tor/. Binaries heissen pokerbench-eichung-tor-<marke>.exe."""
import sys
sys.dont_write_bytecode = True
import argparse, collections, glob, hashlib, json, os, shutil
HIER = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HIER)
import preis as PR # noqa: E402
import turn as TU # noqa: E402
LIVE = "D:/Projects/pokerfreak/.claude/worktrees/engine-lecks-angreifen-de7b88"
GS = os.path.join(os.path.expanduser("~"), "pokerfreak-regulars", "gewinnerspots")
TOR = os.path.join(PR.AUS, "tor")
ITER = "hu_river:100,hu_turn:38,hu_flop:40,mw_flop:2000,mw_turn:2700,mw_river:5600"
SCHWELLE = 2.0
EICHSTAND = {"river": "Eichstand 23.11. (tor.py eichung, eigene Echtgeld-Haende 15.-22.11.): CHECK-Preise stimmen (Abstand +0,0 bb/100), "
"BET-Preise liegen 15,5 ±5,6 bb/100 UEBER dem Echten (gecallte Einsaetze: Siegchance 0,43 vorhergesagt, 0,30 echt). "
"Ein Plus aus 'Richtung CHECK>BET' oder 'BET Groesse' ist deshalb zu hoch und traegt keine Prognose; "
"ein Plus aus 'Richtung BET>CHECK' ist vorsichtig (eher zu klein).",
"turn": "Eichstand 23.11. Turn (eigene Echtgeld-Haende): CHECK-Preise stimmen (Abstand -0,0 bis -0,7), BET-Preise liegen "
"UEBER dem Echten, v. a. OOP/barrel (-9 ±4,6 Feld, -12 ±4,6 Gewinner). Ein Plus aus 'Richtung CHECK>BET' oder "
"'BET Groesse' traegt keine Prognose; 'Richtung BET>CHECK' ist vorsichtig."}
class Strasse:
"""Adapter je Strasse: Daten, Tafeln, Preis, Gewichte, Nullprobe, Dateinamen."""
def __init__(self, name):
self.name = name
self.s = {"river": 3, "turn": 2, "flop": 1}[name]
self.suffix = "" if name == "river" else "_" + name
self.zeile = {"river": "River ohne Einsatz vor uns", "turn": "Turn ohne Einsatz vor uns", "flop": "Flop ohne Einsatz vor uns"}[name]
self.kf = "k" if name == "river" else "kr"
self.R = PR.lade_hhd()
self.Rt = TU.lade_turn() if name != "river" else None
self.daten = {"river": self.R, "turn": self.Rt}.get(name) or TU.lade_flop()
def tafeln(self, D, g):
if self.name == "river":
return PR.Tafeln(D, g)
T = TU.TurnTafeln(D, self.R, g) if self.name == "turn" else TU.FlopTafeln(D, self.Rt, self.R, g)
T.kalibriere(D)
return T
def preis(self, T, d, a, B):
k = d[self.kf]
return T.preis(d, a, k, B) if self.name == "river" else T.preis(d, a, k, B)[0]
def nullprobe(self, D, T, W, N):
f = PR.nullprobe if self.name == "river" else TU.nullprobe
return f(D, T, W, N)[self.zeile]
def haelfte(i):
return "a" if int(hashlib.md5(i.split(".")[0].encode()).hexdigest()[0], 16) % 2 == 0 else "b"
def lade(teil, R):
if teil == "alle":
return R, R
tafel = [d for d in R if haelfte(d["id"]) != teil]
pruef = [d for d in R if haelfte(d["id"]) == teil]
return tafel, pruef
def anteil(pruef, g, alle):
"""Anteil der Haende der Gruppe in der Pruefmenge (1 bei Teil alle), fuer die bb/100-Basis."""
h_all = {d["id"].split(".")[0] for d in alle if d["g"] == g}
h_p = {d["id"].split(".")[0] for d in pruef if d["g"] == g}
return len(h_p) / max(len(h_all), 1)
def in_probe(i, anteil):
"""Feste Stichprobe nach Hand-Nr. (alle Spots einer Hand gemeinsam)."""
return anteil >= 1 or int(hashlib.md5(("probe" + i.split(".")[0]).encode()).hexdigest()[:8], 16) / 16 ** 8 < anteil
def probe_anteil(marke, suffix):
"""Stichprobe eines Arms (arm<suffix>.json, sonst 1)."""
p = os.path.join(TOR, "arme", marke, "arm%s.json" % suffix)
if not os.path.exists(p):
return 1.0
return json.load(open(p, encoding="utf-8")).get("anteil", 1.0)
def cmd_spots(a):
S = Strasse(a.strasse)
R = S.daten
ids = set()
ohne = {d["id"] for d in R if d["a"] in ("CHECK", "BET")} # ohne Einsatz vor uns
for g in ("feld", "gew"):
ids |= set(S.tafeln(R, g).gewichte(R)) & ohne
os.makedirs(TOR, exist_ok=True)
gesehen = set()
with open(os.path.join(TOR, "spots%s.jsonl" % S.suffix), "w", encoding="utf-8", newline="\n") as f:
for p in sorted(glob.glob(os.path.join(GS, "spots", "*.jsonl"))):
for z in open(p, encoding="utf-8"):
sp = json.loads(z)
if sp["id"] in ids and sp["id"] not in gesehen and sp["s"] == S.s:
gesehen.add(sp["id"])
f.write(json.dumps({"id": sp["id"], "req": sp["req"]}, separators=(",", ":")) + "\n")
print(len(gesehen), "Anfragen von", len(ids), "gewichteten Spots")
def cmd_arm(a):
sys.path.insert(0, LIVE + "/lesen")
import leckfinder as lf
import roentgen
d = os.path.join(TOR, "arme", a.marke)
os.makedirs(d, exist_ok=True)
exe = os.path.join(d, "pokerbench-eichung-tor-%s.exe" % a.marke)
if not os.path.exists(exe):
shutil.copy2(a.bin, exe)
env = dict(os.environ)
env.update(roentgen.lies_schalter(a.schalter))
env["SOLVER_ZEIT"] = "fest"
env["SOLVER_ITER"] = ITER
for k in a.ohne or ():
env.pop(k, None)
for kv in a.setze or ():
k, v = kv.split("=", 1)
env[k] = v
suf = "" if a.strasse == "river" else "_" + a.strasse
json.dump({"bin": os.path.abspath(a.bin), "schalter": os.path.abspath(a.schalter), "setze": a.setze, "ohne": a.ohne,
"sha256": hashlib.sha256(open(exe, "rb").read()).hexdigest(), "strasse": a.strasse, "anteil": a.anteil},
open(os.path.join(d, "arm%s.json" % suf), "w", encoding="utf-8"), indent=1)
spots = os.path.join(TOR, "spots%s.jsonl" % suf)
block = 500
if a.anteil < 1: # feste Stichprobe nach Hand-Nr., geschachtelt (0,1 liegt in 0,15)
teil = os.path.join(d, "spots%s_anteil%g.jsonl" % (suf, a.anteil))
with open(teil, "w", encoding="utf-8", newline="\n") as f:
for z in open(spots, encoding="utf-8"):
if in_probe(json.loads(z)["id"], a.anteil):
f.write(z)
spots, block = teil, 100
lf.lauf_entscheiden(spots, os.path.join(d, "antw%s.jsonl" % suf), exe, env, prozesse=a.prozesse, block=block)
def antworten(marke, suffix=""):
A = {}
for z in open(os.path.join(TOR, "arme", marke, "antw%s.jsonl" % suffix), encoding="utf-8"):
x = json.loads(z)
A[x["id"]] = x
return A
def kern_aktion(d, x):
"""Antwort -> (Aktion, Einsatz in bb) fuer einen Spot ohne Einsatz vor uns; None wenn leer."""
if not x or x.get("action") not in ("CHECK", "RAISE", "FOLD", "CALL"):
return None
if x["action"] == "RAISE":
return ("BET", (x.get("size") or 0.0) / 0.02)
return ("CHECK", 0.0)
def cmd_vergleich(a):
S = Strasse(a.strasse)
tafel, pruef = lade(a.teil, S.daten)
A, B = antworten(a.a, S.suffix), antworten(a.b, S.suffix)
ant = min(probe_anteil(a.a, S.suffix), probe_anteil(a.b, S.suffix))
out = {"strasse": a.strasse, "teil": a.teil, "A": a.a, "B": a.b, "anteil": ant}
for g in ("feld", "gew"):
T = S.tafeln(tafel, g) # Preise (bei Teil a/b aus der anderen Haelfte)
W = (T if a.teil == "alle" else S.tafeln(pruef, g)).gewichte(pruef) # Ankunft der Pruefmenge
N = PR.BASIS[g] * anteil(pruef, g, S.daten)
null = S.nullprobe(pruef, T, W, N)
werte = collections.defaultdict(list)
summe = collections.Counter()
kipp = collections.Counter()
leer = 0
for d in pruef:
w = W.get(d["id"])
if not w or d["a"] not in ("CHECK", "BET") or not in_probe(d["id"], ant): # ohne Einsatz, Stichprobe
continue
w = w / ant
ea, eb = kern_aktion(d, A.get(d["id"])), kern_aktion(d, B.get(d["id"]))
if ea is None or eb is None:
leer += 1
continue
if ea[0] == eb[0] and (ea[0] == "CHECK" or abs(ea[1] - eb[1]) < 1e-9):
x = 0.0
else:
x = w * (S.preis(T, d, ea[0], ea[1] or None) - S.preis(T, d, eb[0], eb[1] or None))
kipp[(d["li"], eb[0] + ">" + ea[0])] += w
h = d["id"].split(".")[0]
richtung = "Richtung " + (eb[0] + ">" + ea[0] if ea[0] != eb[0] else ea[0] + " Groesse" if ea[0] == "BET" else "gleich")
for key in (d["li"], richtung, S.zeile):
werte[key].append((h, x))
summe[key] += x
res = {}
for key, v in werte.items():
res[key] = {"bb100": 100 * summe[key] / N, "se": 100 * PR.bootstrap(v) / N}
out[g] = {"null": null, "leer": leer, "zeilen": res,
"kipps_je_100": {"%s %s" % k: 100 * v / N for k, v in kipp.most_common(20)}}
ok = abs(null["fehler"]) <= SCHWELLE
print("\n## %s, Gruppe %s (Teil %s): A=%s minus B=%s" % (a.strasse, g, a.teil, a.a, a.b))
print("Nullprobe %s: Fehler %+.2f ±%.2f bb/100 -> %s" % (a.strasse, null["fehler"], null["se"],
"BESTANDEN" if ok else "NICHT BESTANDEN, Zahl ungueltig"))
print("leere Antworten: %d" % leer)
print("| Linie | bb/100 A−B | ±SE |")
for key in sorted(res, key=lambda k: (k == S.zeile, k.startswith("Richtung"), k)):
print("| %s | %+.2f | %.2f |" % (key, res[key]["bb100"], res[key]["se"]))
print("Kipps je 100 Haende:", {k: round(v, 2) for k, v in out[g]["kipps_je_100"].items()})
print()
print(EICHSTAND.get(a.strasse, ""))
p = os.path.join(TOR, "vergleich%s_%s_%s_%s.json" % (S.suffix, a.a, a.b, a.teil))
json.dump(out, open(p, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
print("->", p)
def ziehe_river(d, rng):
"""Turn-Datensatz ohne River (Hand endete am Turn): River zufaellig aus dem Rest-Deck, k_R neu."""
import fluss
tot = set(d["hk"]) | set(d["brett"][:4])
rest = [r + f for r in "23456789TJQKA" for f in "cdhs" if r + f not in tot]
return fluss.staerke(d["hk"], d["brett"][:4] + [rng.choice(rest)])
def cmd_eichung(a):
"""Eichtor: Preis (Tafeln aus hhDealer) unserer gespielten Aktion mit unserer Handstaerke gegen das echte G.
Ohne Einsatz (wie das Tor) und gegen Einsatz getrennt. Bestanden: |Preis - echt| <= 2 SE."""
import pickle, random
S = Strasse(a.strasse)
U = pickle.load(open(os.path.join(PR.AUS, "fluss_uns%s.pkl" % ("" if S.s == 3 else "_s%d" % S.s)), "rb"))
rng = random.Random(7)
if S.s == 2:
for d in U:
if d["kr"] is None and d.get("hk"):
d["kr"] = ziehe_river(d, rng)
N = 7380
pfad = os.path.join(HIER, "eichung.json")
out = json.load(open(pfad, encoding="utf-8")) if os.path.exists(pfad) else {}
teile = (("ohne Einsatz", ("CHECK", "BET")), ("gegen Einsatz", ("FOLD", "CALL", "RAISE"))) if S.s == 3 else \
(("ohne Einsatz", ("CHECK", "BET")),)
for g in ("feld", "gew"):
T = S.tafeln(S.daten, g)
for teil, nur in teile:
werte = []
p = e = 0.0
n = 0
for d in U:
if d["a"] not in nur or d[S.kf] is None:
continue
pr = S.preis(T, d, d["a"], d["b"] or None)
p += pr; e += d["G"]; n += 1
werte.append((d["id"].split(".")[0], pr - d["G"]))
se = PR.bootstrap(werte)
key = "%s|%s" % (g, teil) if S.s == 3 else "%s|%s|%s" % (a.strasse, g, teil)
out[key] = {"n": n, "preis": 100 * p / N, "echt": 100 * e / N, "abstand": 100 * (e - p) / N,
"se": 100 * se / N, "bestanden": abs(e - p) <= 2 * se}
v = out[key]
print("%s %s %s: %d Entscheidungen, Preis %+.2f, echt %+.2f bb/100, Abstand %+.2f ±%.2f -> %s" % (
g, a.strasse, teil, n, v["preis"], v["echt"], v["abstand"], v["se"], "bestanden" if v["bestanden"] else "NICHT bestanden"))
json.dump(out, open(pfad, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
def main():
ap = argparse.ArgumentParser()
sp = ap.add_subparsers(dest="cmd", required=True)
p = sp.add_parser("spots")
p.add_argument("--strasse", default="river", choices=("river", "turn", "flop"))
p = sp.add_parser("arm")
p.add_argument("--strasse", default="river", choices=("river", "turn", "flop"))
p.add_argument("marke")
p.add_argument("--bin", default=os.path.join(LIVE, "target", "release", "rechner.exe"))
p.add_argument("--schalter", default=os.path.join(LIVE, "betrieb", "kern_schalter.txt"))
p.add_argument("--setze", action="append")
p.add_argument("--ohne", action="append")
p.add_argument("--prozesse", type=int, default=8)
p.add_argument("--anteil", type=float, default=1.0, help="feste Stichprobe der Haende (Turn-Kern ~20 s je Spot unter Last)")
p = sp.add_parser("vergleich")
p.add_argument("a")
p.add_argument("b")
p.add_argument("--teil", default="alle", choices=("a", "b", "alle"))
p.add_argument("--strasse", default="river", choices=("river", "turn", "flop"))
p = sp.add_parser("eichung")
p.add_argument("--strasse", default="river", choices=("river", "turn"))
a = ap.parse_args()
{"spots": cmd_spots, "arm": cmd_arm, "vergleich": cmd_vergleich, "eichung": cmd_eichung}[a.cmd](a)
if __name__ == "__main__":
main()