diff --git a/messung/motor/temperatur/allin_vergleich.py b/messung/motor/temperatur/allin_vergleich.py new file mode 100644 index 00000000..6639f3d6 --- /dev/null +++ b/messung/motor/temperatur/allin_vergleich.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Compare the all-in lists of arm A and arm B (allin_liste.py output): which rows are new in B, which vanish, which stay; per row the +evidence of B's move ("ohne Beleg" for the table mixture without computation). + + python3 allin_vergleich.py +""" +from __future__ import annotations + +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from tor1_lesen import wert # noqa: E402 + + +def zeilen(p): + kopf, out = None, {} + for z in open(p, encoding="utf-8"): + if not z.strip() or z.startswith("#"): + continue + t = z.rstrip("\n").split("\t") + if kopf is None: + kopf = t + continue + out[int(t[0])] = dict(zip(kopf, t)) + return kopf, out + + +def beleg(weg: str, antwort: dict) -> str: + if weg.startswith("Tafel"): + return "ohne Beleg (Tafel-Mischung, keine Rechnung)" + w = wert(antwort) + return w or weg + + +def main(pa, pb, b_gesamt, ziel): + kopf, A = zeilen(pa) + _, B = zeilen(pb) + antworten = {json.loads(z)["zeile"]: json.loads(z)["antwort"] for z in open(b_gesamt, encoding="utf-8")} + rows = [] + for i in sorted(set(A) | set(B)): + stand = "beide" if i in A and i in B else ("neu in B" if i in B else "nur in A (verschwindet)") + r = B.get(i) or A[i] + rows.append([stand] + [r.get(k, "") for k in kopf] + [beleg(r.get("weg", ""), antworten.get(i, {})) if i in B else ""]) + if os.path.exists(ziel): + raise SystemExit(f"existiert schon: {ziel}") + with open(ziel + ".tmp", "w", encoding="utf-8") as f: + f.write("\t".join(["stand"] + kopf + ["beleg_B"]) + "\n") + for r in rows: + f.write("\t".join(str(x).replace("\t", " ") for x in r) + "\n") + os.replace(ziel + ".tmp", ziel) + from collections import Counter + print(Counter(r[0] for r in rows)) + print("ohne Beleg in B:", sum(1 for r in rows if r[0] != "nur in A (verschwindet)" and r[-1].startswith("ohne Beleg"))) + print("neu in B ohne Beleg:", sum(1 for r in rows if r[0] == "neu in B" and r[-1].startswith("ohne Beleg"))) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/messung/motor/temperatur/tor1_lesen.py b/messung/motor/temperatur/tor1_lesen.py new file mode 100644 index 00000000..4970889e --- /dev/null +++ b/messung/motor/temperatur/tor1_lesen.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Reading material for Tor 1 of a version (main judges): merge arm B, replay share of the base, deviation list with request, +mixture, reason, source and computed value, flop deviations grouped by mechanism, Antwortkurve summary for the river. + + python3 tor1_lesen.py [] + +: ein-tor1.jsonl, A/aus-A-{0..3}.jsonl, A/aus-A-river-neu.jsonl, B/aus-B-{0..3}.jsonl, B/aus-B-river-neu.part*.jsonl. +River: both arms are replaced by their river-neu rows (MOTOR_TEMPERATUR_MS=60000, deterministic), as in tor1_fassung.py. + (optional): arm B of the previous version on the same requests; a flop library hit of B that the previous version did not +have is "new" (new pot type or the wider bet band), one it had is "as before". All outputs are new files; nothing is overwritten. +Outputs contain our own cards, board and history (no player keys). +""" +from __future__ import annotations + +import glob +import json +import os +import re +import sys +from collections import Counter, defaultdict + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from tor1_fassung import gruppe # noqa: E402 + +KARTE = {"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"} +FARBE = {"CLUBS": "c", "DIAMONDS": "d", "HEARTS": "h", "SPADES": "s"} +NEUE_TOPFARTEN = ("limp-pool", "limpraise") + + +def lies(p): + return [json.loads(z) for z in open(p, encoding="utf-8-sig") if z.strip()] + + +def schreibe(pfad: str, inhalt: str) -> None: + if os.path.exists(pfad): + raise SystemExit(f"existiert schon, wird nie ueberschrieben: {pfad}") + with open(pfad + ".tmp", "w", encoding="utf-8") as f: + f.write(inhalt) + os.replace(pfad + ".tmp", pfad) + + +def arm(ordner: str, a: str, teile_neu: list[str]) -> list[dict]: + X = sum((lies(os.path.join(ordner, a, f"aus-{a}-{t}.jsonl")) for t in range(4)), []) + for p in teile_neu: + for z in lies(p): + X[z["zeile"]] = z["antwort"] + return X + + +def karten(cs) -> str: + return "".join(KARTE.get(c.get("rank"), "?") + FARBE.get(c.get("suit"), "?") for c in cs or []) + + +def brett(q) -> str: + b = q.get("board") or {} + return " ".join(karten(b.get(s)) for s in ("FLOP", "TURN", "RIVER") if b.get(s)) + + +def verlauf(q) -> str: + return " ".join(f"{h.get('street', '')[:1]}{h.get('seat')}:{h.get('action')}{'' if h.get('amount') is None else ' ' + str(h.get('amount'))}" + for h in q.get("history", []) if h.get("action") not in ("POST_SB", "POST_BB")) + + +def quelle(b: dict) -> str: + g = str(b.get("reason") or "") + if "Jam-Probe" in g: + return "Jamprobe(-Pool)" + if g.startswith("Antwortkurve") or isinstance(b.get("antwortkurve"), dict) and b["antwortkurve"].get("abgewichen"): + return "Antwortkurve" + if g.startswith("Temp(") or b.get("ausbeute"): + return "Temperatur" + if "Bibliothek" in g: + return "Bibliothek" + if "Uhr:" in g: + return "Uhr-Rueckfall" + if re.search(r"FLOP exakt", g): + return "Flop exakt" + if re.search(r"(TURN|RIVER) genau", g): + return "Turn/River genau" + if "preis:" in g: + return "Preisweg" + if "im Topf, Klasse" in g: + return "Tafel" + return "sonst" + + +def wert(b: dict) -> str: + """Computed value of B's choice, where one exists: library/exact Q per move, curve EV, jam probe value.""" + teile = [] + if isinstance(b.get("werte"), list): + teile.append("Q je Zug (bb): " + ", ".join(f"{w[1]}:{w[3]}" for w in b["werte"] if isinstance(w, list) and len(w) > 3 and w[3] is not None)) + ak = b.get("antwortkurve") + if isinstance(ak, dict) and isinstance(ak.get("bayes"), dict): + y = ak["bayes"] + teile.append(f"Kurven-Gewinn gegen Basis {y.get('mittel_bb'):.2f} bb [{y.get('lo_bb'):.2f}; {y.get('hi_bb'):.2f}]") + m = re.search(r"Wert ([+-]?[\d.]+) bb", str(b.get("reason") or "")) + if m: + teile.append(f"Jam-Wert {m.group(1)} bb") + return "; ".join(teile) + + +def topfart(g: str) -> str | None: + m = re.search(r"Bibliothek (\S+)", g) + return m.group(1) if m else None + + +def flop_gruppe(i: int, a: dict, b: dict, alt_b: list[dict] | None) -> str: + ga, gb = str(a.get("reason") or ""), str(b.get("reason") or "") + if "Bibliothek" in gb: + art = topfart(gb) or "?" + if any(art.endswith(n) for n in NEUE_TOPFARTEN): + return f"Bibliothek, neue Topfart ({art})" + if alt_b is not None and "Bibliothek" not in str(alt_b[i].get("reason") or ""): + return "Bibliothek, neu getroffen (Einsatz-Band 0,66-1,5 bzw. neue Stufe)" + return "Bibliothek wie Vorfassung (Treffer schon in 86911151)" + if "FLOP exakt" in ga and "FLOP exakt" not in gb or "FLOP exakt" in gb and "FLOP exakt" not in ga: + return "Flop exakt in der Frist fertig in nur einem Arm (Last/Uhr)" + if "FLOP exakt" in ga and "FLOP exakt" in gb: + return "Flop exakt beide, andere Loesung" + return "sonst (" + quelle(b) + ")" + + +def zug(d): + return (d.get("action"), d.get("size")) + + +def main(lauf: str, ziel: str, vorfassung: str | None = None) -> int: + os.makedirs(ziel, exist_ok=True) + q = lies(os.path.join(lauf, "ein-tor1.jsonl")) + A = arm(lauf, "A", [os.path.join(lauf, "A", "aus-A-river-neu.jsonl")]) + B = arm(lauf, "B", sorted(glob.glob(os.path.join(lauf, "B", "aus-B-river-neu.part*.jsonl")))) + if not (len(q) == len(A) == len(B)): + raise SystemExit(f"Zeilenzahl ungleich: {len(q)} {len(A)} {len(B)}") + alt_b = None + if vorfassung: + alt_b = sum((lies(os.path.join(vorfassung, f"aus-B-{t}.jsonl")) for t in range(4)), []) + schreibe(os.path.join(ziel, "aus-B-gesamt.jsonl"), "".join(json.dumps({"zeile": i, "antwort": b}, ensure_ascii=False) + "\n" for i, b in enumerate(B))) + + ohne_n = ohne_gleich = 0 + abw, je_art, je_flop, river_ak = [], Counter(), defaultdict(list), defaultdict(list) + for i, (r, a, b) in enumerate(zip(q, A, B)): + g = gruppe(a, b) + if g is None: + ohne_n += 1 + ohne_gleich += zug(a) == zug(b) + if zug(a) == zug(b): + continue + s = r.get("street") + e = {"id": i, "strasse": s, "spieler": 1 + sum(1 for v in r.get("villains", []) if not v.get("folded")), + "hand": karten(r.get("heroCards")), "brett": brett(r), "verlauf": verlauf(r), + "topf_bb": round(float(r.get("pot", 0)) / float(r.get("bigBlind") or 0.02), 2), + "alt": f"{a.get('action')} {a.get('size')}", "neu": f"{b.get('action')} {b.get('size')}", + "grund_alt": str(a.get("reason"))[:300], "grund_neu": str(b.get("reason"))[:300], + "quelle_neu": quelle(b), "wert_neu": wert(b), "art": g or "ohne Marke"} + if s == "FLOP": + e["flop_gruppe"] = flop_gruppe(i, a, b, alt_b) + je_flop[e["flop_gruppe"]].append(i) + if s == "RIVER" and e["quelle_neu"] == "Antwortkurve": + ak = b.get("antwortkurve", {}).get("bayes", {}) + river_ak[f"{a.get('action')} -> {b.get('action')}" + (" (Groesse)" if a.get("action") == b.get("action") else "")].append(ak.get("mittel_bb") or 0.0) + je_art[e["art"]] += 1 + abw.append(e) + summe = {"anfragen": len(q), "abweichungen": len(abw), "je_strasse": dict(Counter(e["strasse"] for e in abw)), "je_art": dict(je_art), + "A_wiedergabe": {"n_ohne_marke": ohne_n, "gleich": ohne_gleich, "anteil": ohne_gleich / max(ohne_n, 1)}, + "flop_gruppen": {k: len(v) for k, v in je_flop.items()}, + "river_antwortkurve": {k: {"n": len(v), "summe_kurven_gewinn_bb": round(sum(v), 2)} for k, v in river_ak.items()}, + "b_gilt": "B = aus-B-0..3, die 460 River-Zeilen ersetzt durch aus-B-river-neu.part0/1 (MOTOR_TEMPERATUR_MS=60000, deterministisch); " + "A ebenso durch aus-A-river-neu (gleiches Verfahren wie tor1_fassung.py fuer 86911151)"} + schreibe(os.path.join(ziel, "summe.json"), json.dumps(summe, indent=1, ensure_ascii=False)) + schreibe(os.path.join(ziel, "abweichungen-B.json"), json.dumps(abw, indent=1, ensure_ascii=False)) + print(json.dumps(summe, indent=1, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:]))