Files
pokerfreak/score/abfrage.py
T

253 lines
11 KiB
Python

#!/usr/bin/env python3
"""Asks a version (motor exe + switch line) at the spots of the score and writes its mixture per hand on the reference menu.
python3 score/abfrage.py --fassung basis-rein --exe <motor.exe> --schalter <kern_schalter.txt> [--arm B] --daten <grundstrategie/motor>
--refs <dir of reference files> --spots score/spotsatz-v1.jsonl --pi-dir <dir> [--modus auto|knoten|einzeln] [--seeds 4]
[--prozesse 2] [--extra K=V;K=V] [--street RIVER] [--ranks 0,1]
Two ways to read the mixture of the version at a spot (see `messung.py` for the mapping onto the reference menu):
knoten one request with MOTOR_KNOTEN_MESS=1: the answer carries `knoten_mischung` with the mixture of ALL hands of the range;
hands of the reference the motor does not have in its range are asked one by one (up to --max-fehlend), the rest play the
reference mixture and their probability mass is recorded (`fehlend_w`).
einzeln the 1,326 single requests (hero cards exchanged, --seeds seeds each): expensive, for river spots and small samples.
Output: `<pi-dir>/<spot>.<fassung>.json` = {"profiles": {fassung: {hand: [p per menu action]}}, "meta": {...}} written atomically.
The motor is started like the live runner does: `<exe> dienst sechs100 <daten> 2000-600-400 <km> <daten>/sechs100-v2.bin genau hu=...`.
"""
import argparse, json, os, queue, subprocess, sys, threading, time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import messung as M
RANKS = "23456789TJQKA"
SUITS = "cdhs"
RANK_NAMES = ["TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"]
SUIT_NAMES = ["CLUBS", "DIAMONDS", "HEARTS", "SPADES"]
NO_SERVICES = ("MOTOR_SUCHE", "MOTOR_HYB", "MOTOR_SHARINGAN") # only the motor plays, no live service is touched
LOW_PRIORITY = (0x4000 | 0x08000000) if os.name == "nt" else 0
BIG_BLIND_CHIPS = 100
def canon(hand):
"""'AsKd' / 'KdAs' -> 'KdAs' (lower card first, rank then suit c d h s)."""
cards = [hand[0:2], hand[2:4]]
cards.sort(key=lambda c: (RANKS.index(c[0]), SUITS.index(c[1])))
return "".join(cards)
def card_q(c):
return {"rank": RANK_NAMES[RANKS.index(c[0])], "suit": SUIT_NAMES[SUITS.index(c[1])]}
def with_hole(q, hand):
return {**q, "heroCards": [card_q(hand[0:2]), card_q(hand[2:4])]}
def read_switches(path, arm="A", live_only_motor=True):
"""kern_schalter.txt (K=V per line, '#' comments) -> environment of the version; arm B applies the `AB_SPOT_B=K=V;K=V` line on top."""
env, raw = {}, {}
with open(path, encoding="utf-8") as f:
for line in f:
line = line.split("#", 1)[0].strip()
if "=" in line:
k, v = (t.strip() for t in line.split("=", 1))
raw[k] = v
if k.startswith("MOTOR_") and v and not k.startswith(NO_SERVICES):
env[k] = v
if arm == "B":
for part in (raw.get("AB_SPOT_B") or "").split(";"):
if "=" in part:
k, v = (t.strip() for t in part.split("=", 1))
if k:
env[k] = v
return env
def parse_extra(text):
env = {}
for part in filter(None, (text or "").split(";")):
k, _, v = part.partition("=")
env[k.strip()] = v.strip()
return env
class Motor:
def __init__(self, exe, env, daten, km="200"):
e = {k: v for k, v in os.environ.items() if not k.startswith("MOTOR_")}
e.update(env)
d = daten
self.p = subprocess.Popen(
[exe, "dienst", "sechs100", d, "2000-600-400", km, f"{d}/sechs100-v2.bin", "genau", f"hu={d}/hu100-v1.bin,{d}/hu200-v2.bin"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", env=e,
creationflags=LOW_PRIORITY, preexec_fn=None if os.name == "nt" else (lambda: os.nice(10)))
def ask(self, q, seed):
self.p.stdin.write(json.dumps({**q, "seed": seed}) + "\n")
self.p.stdin.flush()
line = self.p.stdout.readline()
return json.loads(line) if line else {"fehler": "process dead"}
def close(self):
self.p.kill()
def menu_entry(e):
"""Entry of `menue`: [art 0/1/2, size in bb] (cf10eedc) or [FOLD|CHECK|CALL|RAISE|BET|ALL_IN, size in bb, 0] (old base) -> (art, size)."""
a, size = e[0], e[1]
if isinstance(a, str):
a = {"FOLD": 0, "CHECK": 1, "CALL": 1}.get(a.upper(), 2)
return a, size
def profile_from_knoten(ref, knoten):
"""`knoten_mischung` -> ({canon hand: [p per reference action]}, mean distance of the sizes in pot fractions)."""
n = len(ref["actions"])
maps = [M.map_menu_entry(ref, *menu_entry(e)) for e in knoten["menue"]]
out, dists = {}, []
for hand, ps in knoten["haende"]:
pi = [0.0] * n
for p, (m, d) in zip(ps, maps):
for i, x in m.items():
pi[i] += p * x
if d is not None and p > 0:
dists.append(d)
s = sum(pi)
out[canon(hand)] = [x / s for x in pi] if s > 0 else pi
return out, (sum(dists) / len(dists) if dists else None)
def profile_einzeln(ref, motor, q, hands, seeds, base_seed):
"""One request per hand and seed -> ({canon hand: [p]}, mean distance)."""
n = len(ref["actions"])
out, dists = {}, []
for hi, hand in enumerate(hands):
answers = [motor.ask(with_hole(q, hand), base_seed + 7919 * k + hi) for k in range(seeds)]
pi, d = M.mixture(ref, [a for a in answers if "action" in a], q["bigBlind"])
out[canon(hand)] = [pi.get(i, 0.0) for i in range(n)]
if d is not None:
dists.append(d)
return out, (sum(dists) / len(dists) if dists else None)
def complete(ref, profile):
"""Hands of the reference the version gave no mixture for play the reference mixture; returns (profile, missing probability mass)."""
missing, full = 0.0, dict(profile)
for h in ref["hands"]:
c = canon(h["c"])
if c not in full:
full[c] = list(h["sigma"])
missing += h["w"]
return full, missing
def spot_file(sid):
return "".join(c if c.isalnum() else "_" for c in sid) + ".json"
def write_atomic(path, obj):
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(obj, f)
os.replace(tmp, path)
def run_spot(motor, spot, ref, args):
q = spot["q"]
hands = [h["c"] for h in ref["hands"]]
t0, mode, dist, missing_n = time.time(), args.modus, None, 0
prof, extra_profile = None, {}
if args.modus in ("auto", "knoten"):
a = motor.ask(q, spot["req"]["options"].get("seed", 1))
kn = a.get("knoten_mischung") # what the version really plays (after the NL2 rules): the one the score uses
if kn and a.get("knoten_loeser"):
lp, _ = profile_from_knoten(ref, a["knoten_loeser"])
lp, _ = complete(ref, lp)
extra_profile = {args.fassung + "@loeser": lp}
if kn:
prof, dist = profile_from_knoten(ref, kn)
mode = "knoten"
absent = [h for h in hands if canon(h) not in prof]
missing_n = len(absent)
if absent and len(absent) <= args.max_fehlend:
extra, _ = profile_einzeln(ref, motor, q, absent, args.seeds, 1)
prof.update(extra)
elif args.modus == "knoten":
return {"fehler": "no knoten_mischung in the answer: " + json.dumps(a)[:200]}
if prof is None:
prof, dist = profile_einzeln(ref, motor, q, hands, args.seeds, spot["req"]["options"].get("seed", 1))
mode = "einzeln"
prof, miss = complete(ref, prof)
return {"profiles": {args.fassung: prof, **extra_profile},
"meta": {"fassung": args.fassung, "modus": mode, "abstand_mittel": dist, "fehlend_w": miss, "fehlend_haende": missing_n, "sekunden": time.time() - t0}}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--fassung", required=True)
ap.add_argument("--exe", required=True)
ap.add_argument("--schalter", required=True)
ap.add_argument("--arm", default="A", choices=("A", "B"))
ap.add_argument("--daten", required=True)
ap.add_argument("--km", default="200")
ap.add_argument("--extra", default="")
ap.add_argument("--refs", required=True)
ap.add_argument("--spots", default=os.path.join(HERE, "spotsatz-v1.jsonl"))
ap.add_argument("--pi-dir", required=True)
ap.add_argument("--modus", default="auto", choices=("auto", "knoten", "einzeln"))
ap.add_argument("--seeds", type=int, default=4)
ap.add_argument("--max-fehlend", type=int, default=40)
ap.add_argument("--prozesse", type=int, default=2)
ap.add_argument("--street", default="")
ap.add_argument("--ranks", default="")
a = ap.parse_args()
env = read_switches(a.schalter, a.arm)
env.update(parse_extra(a.extra))
if a.modus in ("auto", "knoten"):
env["MOTOR_KNOTEN_MESS"] = "1"
os.makedirs(a.pi_dir, exist_ok=True)
ranks = {int(x) for x in a.ranks.split(",") if x}
work = queue.Queue()
for line in open(a.spots):
sp = json.loads(line)
if a.street and not sp["stratum"].startswith(a.street):
continue
if ranks and sp["rang"] not in ranks:
continue
rf = os.path.join(a.refs, spot_file(sp["id"]))
out = os.path.join(a.pi_dir, spot_file(sp["id"])[:-5] + "." + a.fassung + ".json")
if not os.path.exists(rf) or os.path.exists(out):
continue
ref = json.load(open(rf))
if "fehler" in ref:
continue
work.put((sp, ref, out))
print(f"{work.qsize()} spots to ask for {a.fassung} ({a.modus})", file=sys.stderr, flush=True)
def worker():
motor = Motor(a.exe, env, a.daten, a.km)
try:
while True:
try:
sp, ref, out = work.get_nowait()
except queue.Empty:
return
try:
res = run_spot(motor, sp, ref, a)
except Exception as e: # a failing spot is reported, never silently zero
res = {"fehler": f"{type(e).__name__}: {e}"}
if "fehler" in res:
print(sp["id"], "FEHLER", res["fehler"], file=sys.stderr, flush=True)
continue
write_atomic(out, res)
print(sp["id"], res["meta"]["modus"], f"{res['meta']['sekunden']:.1f}s", "fehlend_w=%.3f" % res["meta"]["fehlend_w"], file=sys.stderr, flush=True)
finally:
motor.close()
threads = [threading.Thread(target=worker) for _ in range(max(1, a.prozesse))]
[t.start() for t in threads]
[t.join() for t in threads]
if __name__ == "__main__":
main()