score: query driver (knoten_mischung or 1,326 single requests, switch line with arm B), score.py (S, regret against GG, loss list, paired difference with bootstrap, Tor-7 file), aggregation; evaluation mode of sharingan-referenz re-solves with the frozen iterations
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Pure aggregation of the score: spot losses -> bb per 100 hands per area, strength S, paired difference with a bootstrap interval.
|
||||
|
||||
A spot result is a dict with `stratum` ("STREET|potart|art"), `id` and the loss values in chips. The loss of a stratum is the mean over its
|
||||
spots of the evaluated set; its weight is `je100[stratum]` = decisions of that stratum per 100 hands; so one area contributes
|
||||
`je100 * mean_loss_bb` bb per 100 hands. Strata without a spot are not measured and are listed, never counted as zero loss.
|
||||
"""
|
||||
import random
|
||||
|
||||
CHIPS_PER_BB = 100.0
|
||||
|
||||
|
||||
def area_street(stratum):
|
||||
return stratum.split("|")[0]
|
||||
|
||||
|
||||
def area_street_pot(stratum):
|
||||
return "|".join(stratum.split("|")[:2])
|
||||
|
||||
|
||||
def area_all(stratum):
|
||||
return "gesamt"
|
||||
|
||||
|
||||
def weighted_bb100(spots, je100, value, area=area_all):
|
||||
"""-> ({area: bb/100}, [strata of `je100` without a spot]); `value(spot)` in chips."""
|
||||
by_stratum = {}
|
||||
for s in spots:
|
||||
by_stratum.setdefault(s["stratum"], []).append(value(s))
|
||||
out = {}
|
||||
for st, vals in by_stratum.items():
|
||||
a = area(st)
|
||||
out[a] = out.get(a, 0.0) + je100[st] * (sum(vals) / len(vals)) / CHIPS_PER_BB
|
||||
return out, sorted(set(je100) - set(by_stratum))
|
||||
|
||||
|
||||
def strength(v, v0):
|
||||
"""S = 100 * (1 - V / V0): 100 = no loss against the perfect opponent, 0 = as much loss as the calling station."""
|
||||
return None if not v0 else 100.0 * (1.0 - v / v0)
|
||||
|
||||
|
||||
def bootstrap_diff(spots_a, spots_b, je100, value, draws=1000, seed=1):
|
||||
"""Paired difference (a - b) of the total bb/100 on the SAME spots (matched by id), with the 2.5 / 97.5 percentile of a bootstrap over the
|
||||
spots within each stratum. Information about the sampling of the spot set only: it says nothing about the solver."""
|
||||
b_by_id = {s["id"]: s for s in spots_b}
|
||||
pairs = [(s, b_by_id[s["id"]]) for s in spots_a if s["id"] in b_by_id]
|
||||
strata = {}
|
||||
for a, b in pairs:
|
||||
strata.setdefault(a["stratum"], []).append(value(a) - value(b))
|
||||
point = sum(je100[st] * sum(d) / len(d) for st, d in strata.items()) / CHIPS_PER_BB
|
||||
rng = random.Random(seed)
|
||||
res = []
|
||||
for _ in range(draws):
|
||||
tot = 0.0
|
||||
for st, d in strata.items():
|
||||
tot += je100[st] * sum(rng.choice(d) for _ in d) / len(d)
|
||||
res.append(tot / CHIPS_PER_BB)
|
||||
res.sort()
|
||||
return point, (res[int(0.025 * draws)], res[min(draws - 1, int(0.975 * draws))]), len(pairs)
|
||||
+28
-12
@@ -27,6 +27,18 @@ def round_half_up(x):
|
||||
return int(math.floor(x + 0.5))
|
||||
|
||||
|
||||
def map_to(ref, to):
|
||||
"""Raise to `to` chips (total on the street) -> ({action index: probability}, distance in pot fractions)."""
|
||||
raises = [i for i, a in enumerate(ref["actions"]) if a["kind"] == "raise"]
|
||||
jam = [i for i in raises if ref["actions"][i].get("all_in")]
|
||||
if to >= JAM_SHARE * ref["max_raise_to"]:
|
||||
return {(jam or raises)[-1]: 1.0}, 0.0
|
||||
f = (to - ref["cur_bet"]) / (ref["pot"] + ref["to_call"])
|
||||
fracs = [ref["actions"][i]["frac"] for i in raises]
|
||||
m = harmonic(fracs, f)
|
||||
return {raises[j]: p for j, p in m.items()}, min(abs(f - x) for x in fracs)
|
||||
|
||||
|
||||
def map_answer(ref, answer, big_blind):
|
||||
"""-> ({action index: probability}, distance in pot fractions or None). `answer` = {action, size} of the motor, size in money."""
|
||||
acts = ref["actions"]
|
||||
@@ -37,19 +49,23 @@ def map_answer(ref, answer, big_blind):
|
||||
return ({idx["fold"][0]: 1.0} if idx["fold"] else {passive: 1.0}), None
|
||||
if kind in ("CHECK", "CALL"):
|
||||
return {passive: 1.0}, None
|
||||
raises = idx["raise"]
|
||||
if kind not in ("RAISE", "BET", "ALL_IN") or not raises:
|
||||
if kind not in ("RAISE", "BET", "ALL_IN") or not idx["raise"]:
|
||||
return {passive: 1.0}, None
|
||||
jam = [i for i in raises if acts[i].get("all_in")]
|
||||
to = None if kind == "ALL_IN" else round_half_up(answer["size"] / big_blind * CHIPS_PER_BB)
|
||||
if kind == "ALL_IN" or to >= JAM_SHARE * ref["max_raise_to"]:
|
||||
return {(jam or raises)[-1]: 1.0}, 0.0
|
||||
basis = ref["pot"] + ref["to_call"]
|
||||
f = (to - ref["cur_bet"]) / basis
|
||||
fracs = [acts[i]["frac"] for i in raises]
|
||||
m = harmonic(fracs, f)
|
||||
dist = min(abs(f - x) for x in fracs)
|
||||
return {raises[j]: p for j, p in m.items()}, dist
|
||||
if kind == "ALL_IN":
|
||||
return map_to(ref, ref["max_raise_to"])
|
||||
return map_to(ref, round_half_up(answer["size"] / big_blind * CHIPS_PER_BB))
|
||||
|
||||
|
||||
def map_menu_entry(ref, art, size_bb):
|
||||
"""Entry of the motor's `knoten_mischung.menue` (art 0 fold, 1 check/call, 2 bet/raise/all-in to `size_bb` big blinds) -> mapping."""
|
||||
acts = ref["actions"]
|
||||
passive = next(i for i, a in enumerate(acts) if a["kind"] in ("check", "call"))
|
||||
if art == 0:
|
||||
fold = [i for i, a in enumerate(acts) if a["kind"] == "fold"]
|
||||
return ({fold[0]: 1.0} if fold else {passive: 1.0}), None
|
||||
if art == 1:
|
||||
return {passive: 1.0}, None
|
||||
return map_to(ref, round_half_up(size_bb * CHIPS_PER_BB))
|
||||
|
||||
|
||||
def mixture(ref, answers, big_blind):
|
||||
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The score of a version (Fassung): loss against the exact reference at the spots of the frozen spot set, in bb per 100 hands.
|
||||
|
||||
python3 score/score.py --fassung basis-rein --refs <reference dir> --pi-dir <dir of abfrage.py> --eval-dir <dir of sharingan-referenz --refdir>
|
||||
[--basis alte-basis] [--spotsatz score/spotsatz-v1.json] --exe-sha256 <sha> --out <dir>
|
||||
|
||||
Reads the frozen reference files, the mixtures of the version(s) per spot (`abfrage.py`) and the evaluation against the perfect opponent
|
||||
(`sharingan-referenz --pi-dir ... --refdir ...`), writes `score.json`, `score.txt` and `ausbeute_beleg.json`. Never overwrites: an existing
|
||||
output file stops the run.
|
||||
"""
|
||||
import argparse, hashlib, json, os, sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import aggregation as G
|
||||
import messung as M
|
||||
from abfrage import canon, spot_file
|
||||
|
||||
HEADER = [
|
||||
"Gemessen wird die Entscheidung am Spot mit exakter Fortsetzung, nicht die volle Hand.",
|
||||
"S, Wurzel (Untergrenze der Ausnutzbarkeit): Der Gegner spielt nur nach unserer Wurzel-Aktion beste Antwort; unsere Fortsetzung ist die "
|
||||
"exakte Loesung, nicht die Suche der Fassung.",
|
||||
"V0 (Calling-Station: nie folden, nie raisen) ist nur der Nullpunkt der Staerke, keine Decke.",
|
||||
"Regret gegen GG: Verlust gegen den Gleichgewichts-Gegner (Untergrenze von V). Mehrspieler und Vorflop sind nicht gemessen (0 Punkte, Gewicht siehe Luecken).",
|
||||
"G (Gesamt) und Ausbeute A: nicht berechnet (Gegnertypen / q fehlen; w noch nicht entschieden, q noch nicht gemessen).",
|
||||
]
|
||||
|
||||
|
||||
def load(path):
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def action_label(a):
|
||||
return a["kind"] if a["kind"] != "raise" else ("allin" if a.get("all_in") else "raise %.2f pot" % a["frac"])
|
||||
|
||||
|
||||
def shares(ref, pi_of_hand):
|
||||
n = len(ref["actions"])
|
||||
ours, best = [0.0] * n, [0.0] * n
|
||||
for h in ref["hands"]:
|
||||
p = pi_of_hand[h["c"]]
|
||||
for i, x in p.items():
|
||||
ours[i] += h["w"] * x
|
||||
best[max(range(n), key=lambda i: h["q"][i])] += h["w"]
|
||||
lab = [action_label(a) for a in ref["actions"]]
|
||||
top = lambda v: {lab[i]: round(v[i], 3) for i in sorted(range(n), key=lambda i: -v[i])[:3] if v[i] > 0.0005}
|
||||
return top(ours), top(best)
|
||||
|
||||
|
||||
def spot_result(spot, ref, ev_by_name, profile, fassung):
|
||||
"""-> dict with regret (chips) against the GG continuation and, if the evaluation exists, the loss against the perfect opponent."""
|
||||
pi = {h["c"]: {i: p for i, p in enumerate(profile[canon(h["c"])])} for h in ref["hands"]}
|
||||
regret = M.loss_chips(ref, pi)
|
||||
val_gg = sum(h["w"] * sum(s * q for s, q in zip(h["sigma"], h["q"])) for h in ref["hands"])
|
||||
res = {"id": spot["id"], "stratum": spot["stratum"], "regret": regret, "val_gg": val_gg, "v_perfect": None, "v0": None, "floor": None}
|
||||
ev, st, gg = ev_by_name.get(fassung), ev_by_name.get("station"), ev_by_name.get("gg")
|
||||
if ev is not None and st is not None:
|
||||
res["v_perfect"], res["v0"] = val_gg - ev, val_gg - st
|
||||
if gg is not None:
|
||||
res["floor"] = val_gg - gg # a perfect reference mixture would be 0: what the solver leaves
|
||||
res["unsere"], res["beste"] = shares(ref, pi)
|
||||
res["board"], res["in_round"] = ref["board"], ref["in_round"]
|
||||
return res
|
||||
|
||||
|
||||
def collect(fassung, args, spots_meta):
|
||||
out = []
|
||||
for line in open(args.spots):
|
||||
spot = json.loads(line)
|
||||
rf = os.path.join(args.refs, spot_file(spot["id"]))
|
||||
pf = os.path.join(args.pi_dir, spot_file(spot["id"])[:-5] + "." + fassung + ".json")
|
||||
if not (os.path.exists(rf) and os.path.exists(pf)):
|
||||
continue
|
||||
ref, pi = load(rf), load(pf)
|
||||
if "fehler" in ref:
|
||||
continue
|
||||
ef = os.path.join(args.eval_dir, spot_file(spot["id"])) if args.eval_dir else None
|
||||
ev = {}
|
||||
if ef and os.path.exists(ef):
|
||||
ev = {p["name"]: p["ev_chips"] for p in load(ef).get("perfect", []) if p["ev_chips"] is not None}
|
||||
r = spot_result(spot, ref, ev, pi["profiles"][fassung], fassung)
|
||||
r["meta"] = pi["meta"]
|
||||
r["ref_expl_chips"] = ref["ref"].get("exploit_chips")
|
||||
r["pot"] = ref["pot"]
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def summary(res, je100):
|
||||
reg, miss = G.weighted_bb100(res, je100, lambda s: s["regret"])
|
||||
reg_street, _ = G.weighted_bb100(res, je100, lambda s: s["regret"], G.area_street)
|
||||
with_v = [s for s in res if s["v_perfect"] is not None]
|
||||
v, _ = G.weighted_bb100(with_v, je100, lambda s: s["v_perfect"])
|
||||
v0, _ = G.weighted_bb100(with_v, je100, lambda s: s["v0"])
|
||||
flo, _ = G.weighted_bb100([s for s in res if s["floor"] is not None], je100, lambda s: s["floor"])
|
||||
streets = {}
|
||||
for st in ("FLOP", "TURN", "RIVER"):
|
||||
sub = [s for s in with_v if s["stratum"].startswith(st)]
|
||||
a, _ = G.weighted_bb100(sub, je100, lambda s: s["v_perfect"], G.area_street)
|
||||
b, _ = G.weighted_bb100(sub, je100, lambda s: s["v0"], G.area_street)
|
||||
if sub:
|
||||
streets[st] = {"V": a[st], "V0": b[st], "S": G.strength(a[st], b[st]), "n": len(sub)}
|
||||
pot_area = {}
|
||||
for s in with_v:
|
||||
pot_area.setdefault(G.area_street_pot(s["stratum"]), []).append(s)
|
||||
pot_rows = {}
|
||||
for k, sub in pot_area.items():
|
||||
a, _ = G.weighted_bb100(sub, je100, lambda s: s["v_perfect"], lambda x: k)
|
||||
b, _ = G.weighted_bb100(sub, je100, lambda s: s["v0"], lambda x: k)
|
||||
pot_rows[k] = {"V": a[k], "V0": b[k], "S": G.strength(a[k], b[k]), "n": len(sub)}
|
||||
ref_err, _ = G.weighted_bb100([s for s in res if s["ref_expl_chips"] is not None], je100, lambda s: s["ref_expl_chips"])
|
||||
return {"regret_gg_bb100": reg.get("gesamt"), "regret_je_strasse": reg_street, "nicht_gemessene_strata": miss,
|
||||
"V_bb100": v.get("gesamt"), "V0_bb100": v0.get("gesamt"), "S": G.strength(v.get("gesamt", 0.0), v0.get("gesamt", 0.0)) if v else None,
|
||||
"n_spots_mit_S": len(with_v), "S_je_strasse": streets, "S_je_strasse_topfart": pot_rows,
|
||||
"rauschboden_bb100": flo.get("gesamt"), "referenzfehler_obergrenze_bb100": ref_err.get("gesamt")}
|
||||
|
||||
|
||||
def loss_list(res, je100, key):
|
||||
rows = []
|
||||
by = {}
|
||||
for s in res:
|
||||
if s[key] is not None:
|
||||
by.setdefault(s["stratum"], []).append(s)
|
||||
for st, sub in by.items():
|
||||
mean = sum(s[key] for s in sub) / len(sub)
|
||||
worst = sorted(sub, key=lambda s: -s[key])[:3]
|
||||
rows.append({"bereich": st, "verlust_bb100": je100[st] * mean / 100.0, "n_spots": len(sub),
|
||||
"beispiele": [{"spot": w["id"], "brett": w["board"], "linie": w["in_round"], "verlust_bb": w[key] / 100.0, "unsere_mischung": w["unsere"],
|
||||
"beste": w["beste"]} for w in worst]})
|
||||
return sorted(rows, key=lambda r: -r["verlust_bb100"])
|
||||
|
||||
|
||||
def text(name, sm, lst, meta, base_line):
|
||||
S = sm["S"]
|
||||
lines = list(HEADER)
|
||||
lines.append("")
|
||||
lines.append(f"Gesamt NL2 G nicht berechnet - Staerke S {('%.1f' % S) if S is not None else 'n/a'} (S, Wurzel) - Ausbeute A nicht berechnet (Spots v1 {meta['sha256'][:8]}, kein Modell)")
|
||||
lines.append(f"{name}: Verlust V {sm['V_bb100']} bb/100, Calling-Station V0 {sm['V0_bb100']} bb/100, Regret gegen GG {sm['regret_gg_bb100']} bb/100, "
|
||||
f"Rauschboden der Referenz {sm['rauschboden_bb100']} bb/100, Referenzfehler (Obergrenze) {sm['referenzfehler_obergrenze_bb100']} bb/100")
|
||||
if base_line:
|
||||
lines.append(base_line)
|
||||
lines.append("")
|
||||
lines.append("Wo wir die meisten Punkte verlieren (bb/100, gewichtet mit der Haeufigkeit):")
|
||||
for r in lst[:15]:
|
||||
lines.append(f" {r['bereich']:<28} {r['verlust_bb100']:8.3f} ({r['n_spots']} Spots)")
|
||||
for e in r["beispiele"][:2]:
|
||||
lines.append(f" {e['spot']} Brett {e['brett']} Linie {e['linie']} {e['verlust_bb']:.2f} bb unsere {e['unsere_mischung']} beste {e['beste']}")
|
||||
lines.append("")
|
||||
lines.append("Bereich | S | V bb/100 | V0 bb/100 | Spots")
|
||||
for k in sorted(sm["S_je_strasse_topfart"]):
|
||||
r = sm["S_je_strasse_topfart"][k]
|
||||
lines.append(f" {k:<14} {('%.1f' % r['S']) if r['S'] is not None else 'n/a':>6} {r['V']:8.3f} {r['V0']:8.3f} {r['n']}")
|
||||
lj = meta.get("luecken_je100", {})
|
||||
lines.append(f" Vorflop: nicht gemessen, 0 Punkte, Gewicht {lj.get('vorflop', 0):.1f} Entscheidungen je 100 Haende")
|
||||
lines.append(f" Mehrspieler: nicht gemessen, 0 Punkte, Gewicht {lj.get('mehrspieler', 0):.1f} je 100 Haende (optimistisch, echte Zahl <= dieser)")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def beleg(exe_sha, meta, n, diff_reg, ci_reg):
|
||||
"""`ausbeute_beleg.json` in the format of Tor 7 (tests/fassung_tor_spec.py: AUSBEUTE). The pool score and the model need the opponent types: null."""
|
||||
return {"exe_sha256": exe_sha,
|
||||
"modell": None, "hinweis_modell": "von temperatur (temperatur-typen-v1.json, Feld pruefung): noch nicht da",
|
||||
"score": {"spot_satz_sha256": meta["sha256"], "n_spots": n, "pool_diff_bb100": None, "pool_intervall": None,
|
||||
"leitplanke_diff_bb100": diff_reg, "leitplanke_intervall": list(ci_reg) if ci_reg else None,
|
||||
"hinweis": "Leitplanke = Regret gegen GG, Kandidat minus Basis (positiv = schlechter), Intervall = Bootstrap ueber die Spots (nur Auskunft); "
|
||||
"Pool-Score braucht die Typen"}}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--fassung", required=True)
|
||||
ap.add_argument("--basis")
|
||||
ap.add_argument("--refs", required=True)
|
||||
ap.add_argument("--pi-dir", required=True)
|
||||
ap.add_argument("--eval-dir")
|
||||
ap.add_argument("--spots", default=os.path.join(HERE, "spotsatz-v1.jsonl"))
|
||||
ap.add_argument("--spotsatz", default=os.path.join(HERE, "spotsatz-v1.json"))
|
||||
ap.add_argument("--exe-sha256", default="")
|
||||
ap.add_argument("--out", required=True)
|
||||
a = ap.parse_args()
|
||||
meta = load(a.spotsatz)
|
||||
sha = hashlib.sha256(open(a.spots, "rb").read()).hexdigest()
|
||||
if sha != meta["sha256"]:
|
||||
sys.exit(f"spot set SHA {sha} differs from {a.spotsatz}: not the frozen set")
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
for f in ("score.json", "score.txt", "ausbeute_beleg.json"):
|
||||
if os.path.exists(os.path.join(a.out, f)):
|
||||
sys.exit(f"{f} exists in {a.out}: never overwritten")
|
||||
je100 = meta["je100"]
|
||||
res = collect(a.fassung, a, meta)
|
||||
if not res:
|
||||
sys.exit("no spot with reference and mixture of this version")
|
||||
sm = summary(res, je100)
|
||||
key = "v_perfect" if sm["n_spots_mit_S"] else "regret"
|
||||
lst = loss_list(res, je100, key)
|
||||
out = {"kopf": HEADER, "fassung": a.fassung, "spot_satz_sha256": meta["sha256"], "n_spots": len(res), **sm, "verlustliste": lst, "gepaart": False}
|
||||
base_line, diff_reg, ci_reg = "", None, None
|
||||
if a.basis:
|
||||
base = collect(a.basis, a, meta)
|
||||
d, ci, n = G.bootstrap_diff(res, base, je100, lambda s: s["regret"])
|
||||
out.update({"gepaart": True, "basis": a.basis, "n_spots_gepaart": n, "differenz_regret_bb100": d, "intervall": list(ci),
|
||||
"intervall_bedeutung": "Bootstrap ueber die Spots je Stratum (Stichprobe des Spot-Satzes), nur Auskunft; Solver-Zufall ist nicht enthalten (eine Referenz)"})
|
||||
diff_reg, ci_reg = d, ci
|
||||
vs = [s for s in res if s["v_perfect"] is not None]
|
||||
bv = [s for s in base if s["v_perfect"] is not None]
|
||||
if vs and bv:
|
||||
dv, civ, nv = G.bootstrap_diff(vs, bv, je100, lambda s: s["v_perfect"])
|
||||
out.update({"differenz_V_bb100": dv, "intervall_V": list(civ), "n_spots_gepaart_V": nv})
|
||||
base_line = f"gegen {a.basis} auf denselben {n} Spots: Regret-Differenz {d:+.3f} bb/100 [{ci[0]:+.3f}, {ci[1]:+.3f}] (negativ = besser, Intervall nur Spot-Stichprobe)"
|
||||
out["buch_zeile"] = (f"{a.fassung}: S {('%.1f' % sm['S']) if sm['S'] is not None else 'n/a'} (Wurzel), Regret gegen GG {sm['regret_gg_bb100']:.3f} bb/100, "
|
||||
f"{len(res)} Spots v1 {meta['sha256'][:8]}" + (f", gegen {a.basis} {out['differenz_regret_bb100']:+.3f}" if a.basis else ""))
|
||||
txt = text(a.fassung, sm, lst, meta, base_line)
|
||||
for f, content in (("score.json", json.dumps(out, indent=1)), ("score.txt", txt + "\n"),
|
||||
("ausbeute_beleg.json", json.dumps(beleg(a.exe_sha256, meta, len(res), diff_reg, ci_reg), indent=1))):
|
||||
tmp = os.path.join(a.out, f + ".tmp")
|
||||
with open(tmp, "w") as fh:
|
||||
fh.write(content)
|
||||
os.replace(tmp, os.path.join(a.out, f))
|
||||
print(txt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -97,7 +97,7 @@ def build(files, pool, out):
|
||||
"entscheidungen": dict(counts), "je100": {s: 100.0 * c / n_hands for s, c in counts.items()},
|
||||
"im_pool": per_stratum, "abgelehnt": {"%s: %s" % k: v for k, v in rejected.items()},
|
||||
"luecken_je100": {k: 100.0 * v / n_hands for k, v in luecken.items()},
|
||||
"luecke": "Preflop is not covered. Heads-up only: multiway postflop decisions (about a fifth of the postflop decisions) are not covered.",
|
||||
"luecke": "Preflop is not covered. Heads-up only: multiway postflop decisions are not covered (see luecken_je100).",
|
||||
}
|
||||
with open(os.path.join(out, SET_NAME + ".json"), "w") as fh:
|
||||
json.dump(meta, fh, indent=1, sort_keys=True)
|
||||
|
||||
@@ -127,7 +127,11 @@
|
||||
"TURN|srp|gegen_einsatz": 2.301626908873141,
|
||||
"TURN|srp|gegen_raise": 0.21758658548757362
|
||||
},
|
||||
"luecke": "Preflop is not covered. Heads-up only: multiway postflop decisions (about a fifth of the postflop decisions) are not covered.",
|
||||
"luecke": "Preflop is not covered. Heads-up only: multiway postflop decisions are not covered (see luecken_je100).",
|
||||
"luecken_je100": {
|
||||
"mehrspieler": 5.769038826230163,
|
||||
"vorflop": 104.68909072761753
|
||||
},
|
||||
"n_spots": 401,
|
||||
"name": "spotsatz-v1",
|
||||
"note": "Proxy for the live frequencies: all motor requests of the shadow logs of 24.11.-02.12.2026 (NL2, 2-6 seats). The set is built from request data only; player and hand identifiers are removed.",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Spec of the query helpers (python3 -m unittest score/test_abfrage.py)."""
|
||||
import os, sys, tempfile, unittest
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import abfrage as A
|
||||
from test_messung import REF
|
||||
|
||||
|
||||
class Abfrage(unittest.TestCase):
|
||||
def test_hand_names_are_canonical_lower_card_first(self):
|
||||
self.assertEqual(A.canon("AsKd"), "KdAs")
|
||||
self.assertEqual(A.canon("KdAs"), "KdAs")
|
||||
self.assertEqual(A.canon("7c7d"), "7c7d")
|
||||
self.assertEqual(A.canon("7d7c"), "7c7d")
|
||||
|
||||
def test_hole_cards_are_replaced_in_the_request(self):
|
||||
q = A.with_hole({"heroCards": [], "x": 1}, "AsKd")
|
||||
self.assertEqual([c["rank"] for c in q["heroCards"]], ["ACE", "KING"])
|
||||
self.assertEqual([c["suit"] for c in q["heroCards"]], ["SPADES", "DIAMONDS"])
|
||||
self.assertEqual(q["x"], 1)
|
||||
|
||||
def test_knoten_mischung_maps_onto_the_reference_menu(self):
|
||||
kn = {"menue": [[1, 0.0], [2, 1.0], [2, 1.5]], "haende": [["AsKs", [0.5, 0.25, 0.25]]], "reichweite": [["AsKs", 0.3]]}
|
||||
prof, d = A.profile_from_knoten(REF, kn) # 1.0 bb = 100 chips = 0.5 pot (index 1); 1.5 bb = 150 chips = 0.75 pot
|
||||
p = prof["KsAs"]
|
||||
self.assertAlmostEqual(p[0], 0.5)
|
||||
self.assertAlmostEqual(p[1], 0.25 + 0.25 * 0.375 / 0.875)
|
||||
self.assertAlmostEqual(p[2], 0.25 * (1 - 0.375 / 0.875))
|
||||
self.assertAlmostEqual(sum(p), 1.0)
|
||||
self.assertAlmostEqual(d, (0.0 + 0.25) / 2)
|
||||
|
||||
def test_old_base_menu_entries_with_action_names(self):
|
||||
kn = {"menue": [["CHECK", 0, 0], ["RAISE", 1.5, 0]], "haende": [["AsKs", [0.4, 0.6]]], "reichweite": [["AsKs", 1.0]]}
|
||||
prof, d = A.profile_from_knoten(REF, kn)
|
||||
self.assertAlmostEqual(prof["KsAs"][0], 0.4)
|
||||
self.assertAlmostEqual(prof["KsAs"][1], 0.6 * 0.375 / 0.875)
|
||||
self.assertAlmostEqual(d, 0.25)
|
||||
|
||||
def test_missing_hands_play_the_reference_mixture_and_the_mass_is_reported(self):
|
||||
prof, miss = A.complete(REF, {"KsAs": [1.0, 0, 0, 0]})
|
||||
self.assertEqual(prof["2d7c"], REF["hands"][1]["sigma"])
|
||||
self.assertAlmostEqual(miss, 0.75)
|
||||
|
||||
def test_switch_line_with_arm_b(self):
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
|
||||
f.write("MOTOR_A=1\nMOTOR_SUCHE_X=1 # service: dropped\nMOTOR_B=0\nAB_SPOT=MOTOR_B\nAB_SPOT_B=MOTOR_B=1;MOTOR_C=2\nOTHER=3\n")
|
||||
self.assertEqual(A.read_switches(f.name, "A"), {"MOTOR_A": "1", "MOTOR_B": "0"})
|
||||
self.assertEqual(A.read_switches(f.name, "B"), {"MOTOR_A": "1", "MOTOR_B": "1", "MOTOR_C": "2"})
|
||||
os.unlink(f.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Spec of the aggregation (python3 -m unittest score/test_aggregation.py)."""
|
||||
import os, sys, unittest
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import aggregation as G
|
||||
|
||||
JE100 = {"FLOP|srp|eroeffnen": 10.0, "RIVER|srp|eroeffnen": 30.0, "TURN|srp|eroeffnen": 5.0}
|
||||
|
||||
|
||||
def sp(i, st, loss):
|
||||
return {"id": i, "stratum": st, "loss": loss}
|
||||
|
||||
|
||||
SPOTS = [sp("a1", "FLOP|srp|eroeffnen", 100.0), sp("a2", "FLOP|srp|eroeffnen", 300.0), sp("b1", "RIVER|srp|eroeffnen", 100.0)]
|
||||
|
||||
|
||||
class Aggregation(unittest.TestCase):
|
||||
def test_weighted_bb_per_100_hand_computed(self):
|
||||
# flop: 10 decisions per 100 hands x mean 200 chips = 2 bb -> 20 ; river: 30 x 1 bb = 30
|
||||
tot, missing = G.weighted_bb100(SPOTS, JE100, lambda s: s["loss"])
|
||||
self.assertAlmostEqual(tot["gesamt"], 50.0)
|
||||
self.assertEqual(missing, ["TURN|srp|eroeffnen"]) # not measured, not zero
|
||||
by_street, _ = G.weighted_bb100(SPOTS, JE100, lambda s: s["loss"], G.area_street)
|
||||
self.assertAlmostEqual(by_street["FLOP"], 20.0)
|
||||
self.assertAlmostEqual(by_street["RIVER"], 30.0)
|
||||
|
||||
def test_strength_anchor_points(self):
|
||||
self.assertAlmostEqual(G.strength(0.0, 8.0), 100.0)
|
||||
self.assertAlmostEqual(G.strength(8.0, 8.0), 0.0)
|
||||
self.assertAlmostEqual(G.strength(2.0, 8.0), 75.0)
|
||||
self.assertIsNone(G.strength(1.0, 0.0))
|
||||
|
||||
def test_paired_difference_uses_the_same_spots_and_brackets_the_point(self):
|
||||
base = [dict(s, loss=s["loss"] * 2) for s in SPOTS] # twice the loss: cand - base = -(base)/2 per spot
|
||||
point, (lo, hi), n = G.bootstrap_diff(SPOTS, base, JE100, lambda s: s["loss"])
|
||||
self.assertEqual(n, 3)
|
||||
self.assertAlmostEqual(point, -50.0) # 20+30 vs 40+60
|
||||
self.assertLessEqual(lo, point + 1e-9)
|
||||
self.assertGreaterEqual(hi, point - 1e-9)
|
||||
|
||||
def test_pairing_ignores_spots_the_base_does_not_have(self):
|
||||
point, _, n = G.bootstrap_diff(SPOTS, SPOTS[:2], JE100, lambda s: s["loss"])
|
||||
self.assertEqual(n, 2)
|
||||
self.assertAlmostEqual(point, 0.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -50,6 +50,14 @@ class Messung(unittest.TestCase):
|
||||
def test_reference_noise_floor(self):
|
||||
self.assertAlmostEqual(M.reference_loss_chips(REF), 0.0)
|
||||
|
||||
def test_knoten_menu_entries_map_like_answers(self):
|
||||
self.assertEqual(M.map_menu_entry(REF, 1, 0.0)[0], {0: 1.0})
|
||||
self.assertEqual(M.map_menu_entry(REF, 0, 0.0)[0], {0: 1.0}) # no fold on this menu: the passive action
|
||||
m, d = M.map_menu_entry(REF, 2, 1.5) # 150 chips = 0.75 pot
|
||||
self.assertAlmostEqual(m[1], 0.375 / 0.875)
|
||||
self.assertAlmostEqual(d, 0.25)
|
||||
self.assertEqual(M.map_menu_entry(REF, 2, 10.0)[0], {3: 1.0})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""End-to-end spec of score.py on a synthetic spot (python3 -m unittest score/test_score.py): outputs, SHA guard, never overwriting, the Tor-7 file format."""
|
||||
import hashlib, json, os, subprocess, sys, tempfile, unittest
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
from test_messung import REF
|
||||
|
||||
SID = "FLOP|srp|eroeffnen#00"
|
||||
STRATUM = "FLOP|srp|eroeffnen"
|
||||
|
||||
|
||||
def ref_file():
|
||||
r = json.loads(json.dumps(REF))
|
||||
r.update({"board": "2sKdAd", "in_round": [], "ref": {"iters": 100, "exploit_chips": 10.0}, "tag": SID})
|
||||
return r
|
||||
|
||||
|
||||
class ScoreEndToEnd(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.d = tempfile.mkdtemp()
|
||||
for sub in ("refs", "pi", "ev"):
|
||||
os.mkdir(os.path.join(self.d, sub))
|
||||
name = "".join(c if c.isalnum() else "_" for c in SID)
|
||||
json.dump(ref_file(), open(os.path.join(self.d, "refs", name + ".json"), "w"))
|
||||
# version "cand": plays the best action with each hand; version "base": always checks
|
||||
cand = {"KsAs": [0, 1, 0, 0], "2d7c": [1, 0, 0, 0]}
|
||||
base = {"KsAs": [1, 0, 0, 0], "2d7c": [1, 0, 0, 0]}
|
||||
for f, prof in (("cand", cand), ("base", base)):
|
||||
json.dump({"profiles": {f: prof}, "meta": {"modus": "knoten", "abstand_mittel": 0.0, "fehlend_w": 0.0, "sekunden": 1}},
|
||||
open(os.path.join(self.d, "pi", name + "." + f + ".json"), "w"))
|
||||
# value of the reference mixture = 0.25*30 + 0.75*(-5) = 3.75 ; perfect-opponent values (chips) for each profile
|
||||
json.dump({"perfect": [{"name": "gg", "ev_chips": 3.0}, {"name": "station", "ev_chips": -20.0}, {"name": "cand", "ev_chips": 2.5}, {"name": "base", "ev_chips": -2.0}]},
|
||||
open(os.path.join(self.d, "ev", name + ".json"), "w"))
|
||||
self.spots = os.path.join(self.d, "spots.jsonl")
|
||||
open(self.spots, "w").write(json.dumps({"id": SID, "stratum": STRATUM, "rang": 0}) + "\n")
|
||||
self.sha = hashlib.sha256(open(self.spots, "rb").read()).hexdigest()
|
||||
self.meta = os.path.join(self.d, "meta.json")
|
||||
json.dump({"sha256": self.sha, "je100": {STRATUM: 10.0}, "luecken_je100": {"vorflop": 100.0, "mehrspieler": 5.0}}, open(self.meta, "w"))
|
||||
|
||||
def run_score(self, out, fassung="cand", *extra):
|
||||
return subprocess.run([sys.executable, os.path.join(HERE, "score.py"), "--fassung", fassung, "--refs", os.path.join(self.d, "refs"),
|
||||
"--pi-dir", os.path.join(self.d, "pi"), "--eval-dir", os.path.join(self.d, "ev"), "--spots", self.spots,
|
||||
"--spotsatz", self.meta, "--exe-sha256", "A" * 64, "--out", out, *extra], capture_output=True, text=True)
|
||||
|
||||
def test_values_hand_computed(self):
|
||||
out = os.path.join(self.d, "o1")
|
||||
r = self.run_score(out, "cand", "--basis", "base")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
s = json.load(open(os.path.join(out, "score.json")))
|
||||
# cand plays the best action everywhere: regret 0. base always checks: KsAs loses 20 chips at w=.25 -> 5 chips -> 10 per 100 x 0.05 bb = 0.5 bb/100
|
||||
self.assertAlmostEqual(s["regret_gg_bb100"], 0.0)
|
||||
# V(cand) = (3.75-2.5)/100*10 = 0.125 ; V0 = (3.75+20)/100*10 = 2.375 ; S = 100*(1-0.125/2.375)
|
||||
self.assertAlmostEqual(s["V_bb100"], 0.125)
|
||||
self.assertAlmostEqual(s["V0_bb100"], 2.375)
|
||||
self.assertAlmostEqual(s["S"], 100 * (1 - 0.125 / 2.375))
|
||||
self.assertTrue(s["gepaart"])
|
||||
self.assertAlmostEqual(s["differenz_regret_bb100"], -0.5)
|
||||
self.assertIn("Gemessen wird die Entscheidung am Spot mit exakter Fortsetzung, nicht die volle Hand.", open(os.path.join(out, "score.txt")).read())
|
||||
|
||||
def test_tor7_file_format(self):
|
||||
out = os.path.join(self.d, "o2")
|
||||
self.assertEqual(self.run_score(out, "cand", "--basis", "base").returncode, 0)
|
||||
b = json.load(open(os.path.join(out, "ausbeute_beleg.json")))
|
||||
self.assertEqual(set(b) - {"hinweis_modell"}, {"exe_sha256", "modell", "score"})
|
||||
self.assertEqual(set(b["score"]) - {"hinweis"}, {"spot_satz_sha256", "n_spots", "pool_diff_bb100", "pool_intervall", "leitplanke_diff_bb100", "leitplanke_intervall"})
|
||||
self.assertEqual(b["score"]["spot_satz_sha256"], self.sha)
|
||||
self.assertEqual(b["exe_sha256"], "A" * 64)
|
||||
self.assertIsNone(b["modell"]) # no model yet: null with a note, never invented
|
||||
|
||||
def test_a_changed_spot_set_is_refused(self):
|
||||
open(self.spots, "a").write("\n")
|
||||
r = self.run_score(os.path.join(self.d, "o3"))
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertIn("frozen", r.stderr + r.stdout)
|
||||
|
||||
def test_never_overwrites(self):
|
||||
out = os.path.join(self.d, "o4")
|
||||
self.assertEqual(self.run_score(out).returncode, 0)
|
||||
self.assertNotEqual(self.run_score(out).returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -16,6 +16,7 @@ use crate::beliefs::hole_mask;
|
||||
use nlhe::abstraction::{ActionList, BetSizing, Menu};
|
||||
use nlhe::{Action, RakeRule, Step};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RefParams {
|
||||
/// First iteration count; the solve is repeated with the double until the target is met (see `solve_until`).
|
||||
pub iters: u64,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! (existing files are never touched, so a run resumes). The file holds `Q(h, a)` for every hero hand with positive reach.
|
||||
//!
|
||||
//! Own flags: `--spots F --out DIR [--menu reich|mittel] [--iters N --max-iters N --target 0.005] [--floor 0.0002] [--rake nl2|nl5|none] [--pooled]
|
||||
//! [--pi-dir DIR] [--no-measure] [--only ID,ID] [--street FLOP|TURN|RIVER] [--ranks 0,1,2] [--max N] [--workers N] [--max-gb N] [--max-seconds S]`;
|
||||
//! [--pi-dir DIR [--refdir DIR]] [--no-measure] [--only ID,ID] [--street FLOP|TURN|RIVER] [--ranks 0,1,2] [--max N] [--workers N] [--max-gb N] [--max-seconds S]`;
|
||||
//! everything else is `sharingan-serve`'s configuration (`--blueprint`, `--buckets`, `--set`, ...).
|
||||
use serde_json::Value;
|
||||
use sharingan_serve::api::ActRequest;
|
||||
@@ -14,7 +14,7 @@ use sharingan_serve::decide::Core;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const OWN: &[&str] = &["pi-dir", "spots", "out", "menu", "iters", "max-iters", "target", "floor", "rake", "pooled", "no-measure", "only", "street", "ranks", "max", "workers", "max-gb", "max-seconds"];
|
||||
const OWN: &[&str] = &["refdir", "pi-dir", "spots", "out", "menu", "iters", "max-iters", "target", "floor", "rake", "pooled", "no-measure", "only", "street", "ranks", "max", "workers", "max-gb", "max-seconds"];
|
||||
const FLAGS: &[&str] = &["pooled", "no-measure"];
|
||||
|
||||
fn file_name(id: &str) -> String {
|
||||
@@ -101,22 +101,42 @@ fn main() {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// profiles of versions at this spot: `<pi-dir>/<name>.json` = {"profiles": {"version": {"AsKd": [p per menu action], ...}}}
|
||||
let profiles: Vec<(String, search::referenz::Profile)> = own
|
||||
.get("pi-dir")
|
||||
.and_then(|d| std::fs::read_to_string(std::path::Path::new(d).join(file_name(id))).ok())
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.and_then(|v| {
|
||||
v["profiles"].as_object().map(|o| {
|
||||
o.iter()
|
||||
.map(|(name, hands)| {
|
||||
let prof = hands.as_object().map_or_else(Default::default, |h| h.iter().map(|(c, ps)| (c.clone(), ps.as_array().map_or(vec![], |a| a.iter().filter_map(|x| x.as_f64()).collect()))).collect());
|
||||
(name.clone(), prof)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
// profiles of versions at this spot: every file `<pi-dir>/<spot>.<version>.json` = {"profiles": {"version": {"AsKd": [p per menu action], ...}}}
|
||||
let profiles: Vec<(String, search::referenz::Profile)> = own.get("pi-dir").map_or_else(Vec::new, |d| {
|
||||
let stem = file_name(id).trim_end_matches(".json").to_string() + ".";
|
||||
let mut out = vec![];
|
||||
let mut files: Vec<_> = std::fs::read_dir(d).map(|r| r.filter_map(|e| e.ok()).map(|e| e.path()).collect()).unwrap_or_default();
|
||||
files.sort();
|
||||
for f in files {
|
||||
let n = f.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
if !(n.starts_with(&stem) && n.ends_with(".json")) {
|
||||
continue;
|
||||
}
|
||||
let Some(v) = std::fs::read_to_string(&f).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
|
||||
for (name, hands) in v["profiles"].as_object().into_iter().flatten() {
|
||||
let prof = hands.as_object().map_or_else(Default::default, |h| h.iter().map(|(c, ps)| (c.clone(), ps.as_array().map_or(vec![], |a| a.iter().filter_map(|x| x.as_f64()).collect()))).collect());
|
||||
out.push((name.clone(), prof));
|
||||
}
|
||||
}
|
||||
out
|
||||
});
|
||||
// evaluation mode: re-solve with exactly the iterations of the frozen reference file (deterministic: same solution), no measuring
|
||||
let mut rp = rp.clone();
|
||||
if let Some(rd) = own.get("refdir") {
|
||||
let refv = std::fs::read_to_string(std::path::Path::new(rd).join(file_name(id))).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
match refv.as_ref().and_then(|r| r["ref"]["iters"].as_u64()) {
|
||||
Some(it) => {
|
||||
rp.iters = it;
|
||||
rp.max_iters = it;
|
||||
rp.measure = false;
|
||||
rp.max_millis = None;
|
||||
}
|
||||
None => {
|
||||
eprintln!("{id}: no frozen reference in {rd}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let t = std::time::Instant::now();
|
||||
let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| core.referenz(&req, &sets, &rp, pooled, id, &profiles)));
|
||||
let out = match res {
|
||||
|
||||
Reference in New Issue
Block a user