Taken from claude/temperatur-766cbc @ bfd374b18 (tooling and docs only; motor code goes via claude/live-stand). Python specs green on this tree: gegnermodell koerper 24, pruefe 31, range_mass 11, range 22, zellen 26, zertifikat 19; jam_range 84.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
433 lines
21 KiB
Python
433 lines
21 KiB
Python
"""Jam-range table: P(tenth of the jammer's hand | jam, situation), learned on the bought NL2 hands.
|
|
|
|
Pure core (no I/O except `schreibe_neu`/`lade`): bands, cells, shrinkage, kappa choice, check on the held-out days, look-up, bias check.
|
|
The data stage (reading the day files, hand strength) is `jam_range_lauf.py`. Spec: tests/jam_range_spec.py. Format: FORMAT.md next to the output file.
|
|
|
|
Cell = street x jam size band x kind (lead / raise) x way (heads-up / multiway). The jam size is Jam / (pot + call) in the edges KANTEN (j0..j7).
|
|
Stages (finest first): L0 street/band/kind/way, L1 street/band/way, L2 street/way, L3 pool (all streets). Each stage is shrunk to the next coarser one:
|
|
p = (n * own + kappa * parent) / (n + kappa), confidence = n / (n + kappa)
|
|
and a cell without rows is its parent. kappa per stage is chosen by cross-validated log-loss over blocks of learning days (grid KAPPA_GITTER, ties go to the larger kappa); the check days only measure.
|
|
|
|
Rows are a dict of equally long numpy arrays: strasse (0 flop, 1 turn, 2 river), verhaeltnis (Jam / (pot + call)), art (0 lead, 1 raise), weg (0 heads-up, 1 multiway),
|
|
zehntel (0..9, tenth of the jammer's hand strength on that board), datei (day file number). Nothing else is read, so nothing else can leave the core.
|
|
"""
|
|
import sys; sys.dont_write_bytecode = True
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
|
|
import numpy as np
|
|
|
|
KANTEN = (0.6, 1.2, 2.0, 3.0, 5.0, 8.0, 15.0)
|
|
BAND_NAMEN = tuple("j%d" % i for i in range(len(KANTEN) + 1))
|
|
KANTEN_TOLERANZ = 1e-9 # same tolerance as the day-file readers (anteil + 1e-9 >= edge)
|
|
STRASSEN = ("flop", "turn", "river")
|
|
ARTEN = ("lead", "raise")
|
|
WEGE = ("zweiweg", "mehrweg")
|
|
ZEHNTEL = 10
|
|
KAPPA_GITTER = (0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, math.inf)
|
|
LOG_UNTERGRENZE = 1e-12
|
|
FALTEN = 5
|
|
SHA_ENDUNG = ".sha256"
|
|
PERMUTATIONEN = 200
|
|
BOOTSTRAP = 200
|
|
KONFIDENZ_PROZENT = (2.5, 97.5) # 95 % interval of the day bootstrap
|
|
STANDARD_SAMEN = 0 # seed of the bias check when no generator is given
|
|
SCHRANKE_GLEICHSTAND = 1e-12 # kappa ties: losses closer than this count as equal
|
|
FORMAT = "jam-range-gegner-v1"
|
|
STEMPEL = "vorläufig, ohne Zertifikat"
|
|
LERNTAGE = [0, 307]
|
|
PRUEFTAGE = [308, 385]
|
|
|
|
RADIX = {"strasse": len(STRASSEN), "band": len(BAND_NAMEN), "art": len(ARTEN), "weg": len(WEGE)}
|
|
# (stage name, fields); the last stage has no fields: the pool over everything
|
|
STANDARD = (("L0", ("strasse", "band", "art", "weg")), ("L1", ("strasse", "band", "weg")), ("L2", ("strasse", "weg")), ("L3", ()))
|
|
OHNE_BAND = (("L0", ("strasse", "art", "weg")), ("L1", ("strasse", "weg")), ("L2", ()))
|
|
|
|
ZEILEN_FELDER = ("strasse", "verhaeltnis", "art", "weg", "zehntel", "datei")
|
|
VERBOTENE_NAMEN = {"spieler", "gegner", "akteur", "id", "hash", "hand", "hid", "gid", "sp", "schluessel_spieler", "player"}
|
|
GROSSE_ZAHL = 2 ** 40 # anything bigger looks like a hashed key
|
|
ZELLEN_FELDER = {"p", "n", "vertrauen", "stufe"}
|
|
ZELLEN_NAME = re.compile(r"^(pool|(flop|turn|river)/(j[0-7]/)?((lead|raise)/)?(zweiweg|mehrweg))$")
|
|
|
|
|
|
# ---------- bands, kinds, rows ----------
|
|
|
|
def band_von(verhaeltnis):
|
|
"""Band index 0..7 of Jam / (pot + call). A value exactly on an edge falls into the upper band."""
|
|
v = float(verhaeltnis)
|
|
if not math.isfinite(v) or v < 0:
|
|
raise ValueError("Jam/(Topf+Call) must be a finite number >= 0: %r" % (verhaeltnis,)) # pragma: no mutate
|
|
return sum(1 for e in KANTEN if v + KANTEN_TOLERANZ >= e) # pragma: no mutate (`>` differs only at one float: equivalent)
|
|
|
|
|
|
def baender_von(verhaeltnisse):
|
|
v = np.asarray(verhaeltnisse, dtype=float) # pragma: no mutate (int input behaves the same)
|
|
if not np.isfinite(v).all() or (v < 0).any():
|
|
raise ValueError("Jam/(Topf+Call) must be finite and >= 0") # pragma: no mutate
|
|
return sum((v + KANTEN_TOLERANZ >= e).astype(np.int64) for e in KANTEN) # pragma: no mutate (`>` differs only at one float: equivalent)
|
|
|
|
|
|
def art_von_zug(zug):
|
|
"""Move code of the day-file readers: 3 = bet (lead), 4 = raise."""
|
|
if zug == 3:
|
|
return "lead"
|
|
if zug == 4:
|
|
return "raise"
|
|
raise ValueError("a jam is a bet (3) or a raise (4), not move %r" % (zug,)) # pragma: no mutate
|
|
|
|
|
|
def pruefe_zeilen(z):
|
|
n = None
|
|
for k in ZEILEN_FELDER:
|
|
if k not in z:
|
|
raise ValueError("rows lack the field %r" % k) # pragma: no mutate
|
|
if n is None:
|
|
n = len(z[k])
|
|
elif len(z[k]) != n:
|
|
raise ValueError("field %r has the wrong length" % k) # pragma: no mutate
|
|
for k, hoechst in (("strasse", 2), ("art", 1), ("weg", 1), ("zehntel", 9)):
|
|
a = np.asarray(z[k])
|
|
if len(a) and (a.min() < 0 or a.max() > hoechst):
|
|
raise ValueError("field %r outside 0..%d" % (k, hoechst)) # pragma: no mutate
|
|
baender_von(z["verhaeltnis"])
|
|
|
|
|
|
def _werte(z):
|
|
return {"strasse": np.asarray(z["strasse"], dtype=np.int64), "band": baender_von(z["verhaeltnis"]),
|
|
"art": np.asarray(z["art"], dtype=np.int64), "weg": np.asarray(z["weg"], dtype=np.int64)}
|
|
|
|
|
|
def _anzahl_codes(felder):
|
|
return int(np.prod([RADIX[f] for f in felder], dtype=np.int64)) # the empty product is 1: the pool # pragma: no mutate
|
|
|
|
|
|
def _codes(werte, felder):
|
|
c = np.zeros(len(next(iter(werte.values()))), dtype=np.int64)
|
|
for f in felder:
|
|
c = c * RADIX[f] + werte[f]
|
|
return c
|
|
|
|
|
|
def _zerlegen(code, felder):
|
|
out = {}
|
|
for f in reversed(felder):
|
|
code, out[f] = divmod(code, RADIX[f])
|
|
return out
|
|
|
|
|
|
def _eltern_codes(felder, eltern_felder):
|
|
"""For every code of a stage the code of its parent stage."""
|
|
out = np.zeros(_anzahl_codes(felder), dtype=np.int64)
|
|
for c in range(len(out)):
|
|
w = _zerlegen(c, felder)
|
|
k = 0
|
|
for f in eltern_felder:
|
|
k = k * RADIX[f] + w[f]
|
|
out[c] = k
|
|
return out
|
|
|
|
|
|
# ---------- shrinkage ----------
|
|
|
|
def vertrauen(n, kappa):
|
|
"""n / (n + kappa); kappa = infinity gives 0, n = 0 gives 0."""
|
|
if n <= 0 or kappa == math.inf:
|
|
return 0.0
|
|
return float(n) / (float(n) + float(kappa))
|
|
|
|
|
|
def schrumpfe(zaehler, eltern, kappa):
|
|
"""p = (n * own + kappa * parent) / (n + kappa); no rows or kappa = infinity: the parent; kappa = 0: the own frequencies."""
|
|
zaehler = np.asarray(zaehler, dtype=float) # pragma: no mutate (int input behaves the same)
|
|
eltern = np.asarray(eltern, dtype=float) # pragma: no mutate (int input behaves the same)
|
|
n = zaehler.sum()
|
|
if n == 0 or kappa == math.inf:
|
|
return eltern.copy()
|
|
return (zaehler + kappa * eltern) / (n + kappa)
|
|
|
|
|
|
def _zaehler(z, hierarchie):
|
|
"""Counts [codes, 10] per stage."""
|
|
w = _werte(z)
|
|
zt = np.asarray(z["zehntel"], dtype=np.int64)
|
|
out = {}
|
|
for name, felder in hierarchie:
|
|
k = _anzahl_codes(felder)
|
|
out[name] = np.bincount(_codes(w, felder) * ZEHNTEL + zt, minlength=k * ZEHNTEL).reshape(k, ZEHNTEL).astype(float) # pragma: no mutate
|
|
return out
|
|
|
|
|
|
def _verteilungen(zaehler, kappas, hierarchie, ab=0):
|
|
"""Shrunk distributions [codes, 10] for the stages ab..pool (kappas by stage name; the pool has none)."""
|
|
p = {}
|
|
letzte = len(hierarchie) - 1
|
|
pool = zaehler[hierarchie[letzte][0]][0]
|
|
if pool.sum() == 0:
|
|
raise ValueError("no rows to learn from") # pragma: no mutate
|
|
p[hierarchie[letzte][0]] = (pool / pool.sum())[None, :]
|
|
for i in range(letzte - 1, ab - 1, -1):
|
|
name, felder = hierarchie[i]
|
|
eltern_name, eltern_felder = hierarchie[i + 1]
|
|
zu = _eltern_codes(felder, eltern_felder)
|
|
eltern = p[eltern_name][zu]
|
|
p[name] = np.stack([schrumpfe(zaehler[name][c], eltern[c], kappas[name]) for c in range(len(zu))])
|
|
return p
|
|
|
|
|
|
def _logloss(p, test_zaehler):
|
|
"""Mean -log p of the test rows; p and the test counts are [codes, 10] of the same stage."""
|
|
return float(-(test_zaehler * np.log(np.maximum(p, LOG_UNTERGRENZE))).sum() / test_zaehler.sum())
|
|
|
|
|
|
def tagesfalten(dateien, k):
|
|
"""Blocks of consecutive days (by day number) for cross-validation; fewer days than k give one fold per day; a single day cannot be folded."""
|
|
tage = np.unique(np.asarray(dateien))
|
|
if len(tage) < 2:
|
|
raise ValueError("cross-validation needs at least two days") # pragma: no mutate
|
|
return np.array_split(tage, min(k, len(tage)))
|
|
|
|
|
|
def _falten_verlust(falte, gesamt, kappas, hierarchie, stufe):
|
|
"""Rows x mean log-loss of one held-out fold, predicted from all the other folds."""
|
|
train = {nm: gesamt[nm] - falte[nm] for nm, _ in hierarchie}
|
|
name = hierarchie[stufe][0]
|
|
p = _verteilungen(train, kappas, hierarchie, ab=stufe)
|
|
return falte[name].sum() * _logloss(p[name], falte[name])
|
|
|
|
|
|
def waehle_kappas(lern, falten=FALTEN, hierarchie=STANDARD):
|
|
"""kappa per stage by cross-validated log-loss over blocks of days INSIDE the learning days (check days are refused), coarse to fine: the finer stage sees the chosen
|
|
kappa of the coarser ones. Each fold is predicted from the other folds only; the loss is the row-weighted mean over the folds. Ties go to the larger kappa."""
|
|
pruefe_zeilen(lern)
|
|
if len(lern["datei"]) and np.asarray(lern["datei"]).max() > LERNTAGE[1]:
|
|
raise ValueError("the kappa choice only takes learning days (<= %d)" % LERNTAGE[1]) # pragma: no mutate
|
|
tage = np.asarray(lern["datei"])
|
|
je_falte = [_zaehler({k: np.asarray(v)[np.isin(tage, f)] for k, v in lern.items()}, hierarchie) for f in tagesfalten(tage, falten)]
|
|
gesamt = {name: sum(z[name] for z in je_falte) for name, _ in hierarchie}
|
|
n_gesamt = len(tage)
|
|
kappas, je_kappa = {}, {}
|
|
for i in range(len(hierarchie) - 2, -1, -1):
|
|
name = hierarchie[i][0]
|
|
verluste = []
|
|
for k in KAPPA_GITTER:
|
|
verluste.append(sum(_falten_verlust(z, gesamt, dict(kappas, **{name: float(k)}), hierarchie, i) for z in je_falte) / n_gesamt)
|
|
best = min(verluste)
|
|
wahl = max(j for j, v in enumerate(verluste) if v <= best + SCHRANKE_GLEICHSTAND) # pragma: no mutate (`<` is equivalent: best itself always qualifies)
|
|
kappas[name] = float(KAPPA_GITTER[wahl])
|
|
je_kappa[name] = verluste
|
|
return {"kappa": kappas, "logloss_je_kappa": je_kappa, "gitter": [k if k != math.inf else "inf" for k in KAPPA_GITTER], "falten": len(je_falte)}
|
|
|
|
|
|
# ---------- table ----------
|
|
|
|
def _zellname(felder, code):
|
|
if not felder:
|
|
return "pool"
|
|
w = _zerlegen(code, felder)
|
|
namen = {"strasse": STRASSEN, "band": BAND_NAMEN, "art": ARTEN, "weg": WEGE}
|
|
return "/".join(namen[f][w[f]] for f in felder)
|
|
|
|
|
|
def _kappa_json(k):
|
|
return "inf" if k == math.inf else float(k)
|
|
|
|
|
|
def baue_tafel(lern, kappas, kopf_extra=None):
|
|
"""The table: head, cells (only cells with rows; the pool always). kappas: {"L0": .., "L1": .., "L2": ..}."""
|
|
pruefe_zeilen(lern)
|
|
zaehler = _zaehler(lern, STANDARD)
|
|
p = _verteilungen(zaehler, kappas, STANDARD)
|
|
zellen = {}
|
|
for name, felder in STANDARD:
|
|
for c in range(_anzahl_codes(felder)):
|
|
n = int(zaehler[name][c].sum())
|
|
if n == 0:
|
|
continue
|
|
zellen[_zellname(felder, c)] = {"p": [float(x) for x in p[name][c]], "n": n,
|
|
"vertrauen": 1.0 if not felder else vertrauen(n, kappas[name]), "stufe": name}
|
|
kopf = {"format": FORMAT, "zertifikat": STEMPEL, "lerntage": list(LERNTAGE), "pruefitage": list(PRUEFTAGE), "kanten": list(KANTEN), "baender": list(BAND_NAMEN),
|
|
"kappa": {k: _kappa_json(v) for k, v in kappas.items()}, "quellen_sha256": {}, "zeilen_gelernt": int(len(lern["zehntel"]))}
|
|
kopf.update(kopf_extra or {})
|
|
return {"kopf": kopf, "zellen": zellen}
|
|
|
|
|
|
def nachschlagen(strasse, verhaeltnis, art, mehrweg, *, tafel):
|
|
"""Reference look-up. Finest existing cell wins: L0 street/band/kind/way, then L1 street/band/way, then L2 street/way; a value on a band edge belongs to the
|
|
upper band; nothing found: None. The all-street pool is NOT a fallback. Invalid input (street, kind, ratio, way not a bool) raises ValueError."""
|
|
if strasse not in STRASSEN:
|
|
raise ValueError("street %r, expected one of %s" % (strasse, STRASSEN)) # pragma: no mutate
|
|
if art not in ARTEN:
|
|
raise ValueError("kind %r, expected one of %s" % (art, ARTEN)) # pragma: no mutate
|
|
if not isinstance(mehrweg, (bool, np.bool_)):
|
|
raise ValueError("mehrweg must be a bool: %r" % (mehrweg,)) # pragma: no mutate
|
|
s, b, a, w = strasse, BAND_NAMEN[band_von(verhaeltnis)], art, WEGE[1 if mehrweg else 0]
|
|
for schl in ("/".join((s, b, a, w)), "/".join((s, b, w)), "/".join((s, w))):
|
|
z = tafel["zellen"].get(schl)
|
|
if z is not None:
|
|
return {"verteilung": list(z["p"]), "n": z["n"], "vertrauen": z["vertrauen"], "stufe": z["stufe"], "schluessel": schl}
|
|
return None
|
|
|
|
|
|
def pruefvektoren_bauen(tafel):
|
|
"""Check vectors for a port: every street x kind x way with the ratios 0, just below / on / just above every edge, and 20; the expected answer is `nachschlagen` (None = no cell)."""
|
|
werte = [0.0]
|
|
for e in KANTEN:
|
|
werte += [e - 1e-6, e, e + 1e-6]
|
|
werte.append(20.0)
|
|
return [{"strasse": s, "verhaeltnis": v, "art": a, "mehrweg": w, "erwartet": nachschlagen(s, v, a, w, tafel=tafel)}
|
|
for s in STRASSEN for a in ARTEN for w in (False, True) for v in werte]
|
|
|
|
|
|
# ---------- check on the held-out days ----------
|
|
|
|
def pruefe_gegen_pruefstage(tafel, lern, test, kappas):
|
|
"""Log-loss on the test rows per street (and "alle"): chain of cells, pool, uniform, and cells without the size band (own kappa by log-loss on the same rows)."""
|
|
pruefe_zeilen(test)
|
|
zl = _zaehler(lern, STANDARD)
|
|
p = _verteilungen(zl, kappas, STANDARD)
|
|
ohne = waehle_kappas(lern, hierarchie=OHNE_BAND)
|
|
zl_ohne = _zaehler(lern, OHNE_BAND)
|
|
p_ohne = _verteilungen(zl_ohne, ohne["kappa"], OHNE_BAND)
|
|
out = {}
|
|
strassen = np.asarray(test["strasse"])
|
|
for name, maske in [(STRASSEN[s], strassen == s) for s in range(len(STRASSEN))] + [("alle", np.ones(len(strassen), dtype=bool))]:
|
|
if not maske.any():
|
|
continue
|
|
t = {k: np.asarray(v)[maske] for k, v in test.items()}
|
|
zt = _zaehler(t, STANDARD)
|
|
zt_ohne = _zaehler(t, OHNE_BAND)
|
|
out[name] = {"n": int(maske.sum()),
|
|
"logloss_zelle": _logloss(p["L0"], zt["L0"]),
|
|
"logloss_pool": _logloss(p["L3"][np.zeros(1, dtype=np.int64)], zt["L3"]),
|
|
"logloss_gleichverteilt": math.log(ZEHNTEL),
|
|
"logloss_ohne_band": _logloss(p_ohne["L0"], zt_ohne["L0"]),
|
|
"logloss_je_stufe": {st: _logloss(p[st], zt[st]) for st in ("L0", "L1", "L2")}}
|
|
out["kappa_ohne_band"] = {k: _kappa_json(v) for k, v in ohne["kappa"].items()}
|
|
return out
|
|
|
|
|
|
# ---------- bias check ----------
|
|
|
|
def _verteilung_standardisiert(zaehl, gewicht):
|
|
"""zaehl [strata, 2, 10] -> (dist_tief [10], dist_hoch [10]); strata weighted by `gewicht` (strata with an empty type are left out)."""
|
|
n = zaehl.sum(axis=2)
|
|
ok = (n > 0).all(axis=1)
|
|
if not ok.any():
|
|
return None, None
|
|
w = gewicht[ok] / gewicht[ok].sum()
|
|
return tuple((w[:, None] * (zaehl[ok, t] / n[ok, t][:, None])).sum(axis=0) for t in (0, 1))
|
|
|
|
|
|
def verzerrung_nach_typ(z, typ, tief, hoch, permutationen=PERMUTATIONEN, rng=None, boot=BOOTSTRAP):
|
|
"""Does the jammer's tenth depend on WHO called (type `tief` against `hoch`, e.g. tight against loose callers)? If the call does not depend on the jammer's hand,
|
|
the distribution of the jammer's tenth is the same for every caller type, once the cell mix (street/band/kind/way) is held equal.
|
|
Statistic: total-variation distance between the two cell-mix-standardised distributions, and the difference of the mean tenth (hoch - tief, in tenths).
|
|
p-value: permutation of the type labels within cells. CI of the mean difference: bootstrap over day files (if `datei` varies)."""
|
|
pruefe_zeilen(z)
|
|
rng = rng or np.random.default_rng(STANDARD_SAMEN)
|
|
typ = np.asarray(typ)
|
|
m = np.isin(typ, (tief, hoch))
|
|
zz = {k: np.asarray(v)[m] for k, v in z.items()}
|
|
t = (typ[m] == hoch).astype(np.int64)
|
|
w = _werte(zz)
|
|
schicht = _codes(w, STANDARD[0][1])
|
|
zt = np.asarray(zz["zehntel"], dtype=np.int64)
|
|
ns = _anzahl_codes(STANDARD[0][1])
|
|
|
|
def zaehlen(labels):
|
|
return np.bincount((schicht * 2 + labels) * ZEHNTEL + zt, minlength=ns * 2 * ZEHNTEL).reshape(ns, 2, ZEHNTEL)
|
|
stufe = np.arange(ZEHNTEL)
|
|
|
|
def statistik(zaehl):
|
|
gew = zaehl.sum(axis=(1, 2))
|
|
a, b = _verteilung_standardisiert(zaehl, gew)
|
|
if a is None:
|
|
return float("nan"), float("nan") # pragma: no mutate
|
|
return 0.5 * float(np.abs(a - b).sum()), float((b * stufe).sum() - (a * stufe).sum())
|
|
tv, diff = statistik(zaehlen(t))
|
|
# permutation within cells
|
|
ordnung = np.argsort(schicht, kind="stable") # pragma: no mutate (any sort works, the labels are shuffled anyway)
|
|
s_sorted, t_sorted, z_sorted = schicht[ordnung], t[ordnung], zt[ordnung]
|
|
ueber = 0
|
|
for _ in range(permutationen):
|
|
perm = np.lexsort((rng.random(len(s_sorted)), s_sorted))
|
|
lab = t_sorted[perm]
|
|
zaehl = np.bincount((s_sorted * 2 + lab) * ZEHNTEL + z_sorted, minlength=ns * 2 * ZEHNTEL).reshape(ns, 2, ZEHNTEL)
|
|
if statistik(zaehl)[0] >= tv - 1e-15: # pragma: no mutate (a tolerance: `>` is equivalent)
|
|
ueber += 1
|
|
p_wert = (1 + ueber) / (permutationen + 1)
|
|
ci = None
|
|
tage = np.unique(np.asarray(zz["datei"]))
|
|
if len(tage) > 1 and boot > 0 and len(zt):
|
|
je_tag = np.stack([np.bincount((schicht[zz["datei"] == d] * 2 + t[zz["datei"] == d]) * ZEHNTEL + zt[zz["datei"] == d], minlength=ns * 2 * ZEHNTEL) for d in tage]).astype(float) # pragma: no mutate
|
|
ziehungen = []
|
|
for _ in range(boot):
|
|
gew = np.bincount(rng.integers(0, len(tage), len(tage)), minlength=len(tage)).astype(float) # pragma: no mutate
|
|
ziehungen.append(statistik((gew @ je_tag).reshape(ns, 2, ZEHNTEL))[1])
|
|
ci = [float(np.nanpercentile(ziehungen, q)) for q in KONFIDENZ_PROZENT]
|
|
return {"tv": tv, "mittel_differenz": diff, "p_wert": p_wert, "ci95_mittel_differenz": ci, "n_tief": int((t == 0).sum()), "n_hoch": int((t == 1).sum()),
|
|
"zellen_genutzt": int(((zaehlen(t).sum(axis=2) > 0).all(axis=1)).sum())}
|
|
|
|
|
|
# ---------- output ----------
|
|
|
|
def pruefe_ohne_schluessel(tafel):
|
|
"""Guard: cells have exactly p/n/vertrauen/stufe under a known cell name; nowhere a player-like key name or a hash-sized integer."""
|
|
for name, z in tafel.get("zellen", {}).items():
|
|
if not ZELLEN_NAME.match(name):
|
|
raise ValueError("unexpected cell name %r" % name) # pragma: no mutate
|
|
if set(z) != ZELLEN_FELDER:
|
|
raise ValueError("cell %r has fields %s" % (name, sorted(z))) # pragma: no mutate
|
|
|
|
def gehe(x, pfad):
|
|
if isinstance(x, dict):
|
|
for k, v in x.items():
|
|
if str(k).lower() in VERBOTENE_NAMEN:
|
|
raise ValueError("forbidden key %r at %s" % (k, pfad)) # pragma: no mutate
|
|
gehe(v, pfad + "/" + str(k)) # pragma: no mutate (the path only feeds the message)
|
|
elif isinstance(x, (list, tuple)):
|
|
for v in x:
|
|
gehe(v, pfad)
|
|
elif isinstance(x, (int, np.integer)) and not isinstance(x, bool) and abs(int(x)) >= GROSSE_ZAHL:
|
|
raise ValueError("hash-sized integer at %s" % pfad) # pragma: no mutate
|
|
gehe(tafel, "") # pragma: no mutate
|
|
|
|
|
|
def _atomar_neu(pfad, inhalt):
|
|
tmp = pfad + ".tmp.%d" % os.getpid() # pragma: no mutate
|
|
try:
|
|
with open(tmp, "xb") as f:
|
|
f.write(inhalt)
|
|
if os.path.exists(pfad):
|
|
raise FileExistsError(pfad)
|
|
os.rename(tmp, pfad)
|
|
finally:
|
|
if os.path.exists(tmp):
|
|
os.remove(tmp)
|
|
|
|
|
|
def schreibe_neu(pfad, tafel):
|
|
"""JSON + .sha256 as NEW files (temp file, then rename); never overwrites. Returns the SHA256 of the JSON file."""
|
|
pruefe_ohne_schluessel(tafel)
|
|
if os.path.exists(pfad) or os.path.exists(pfad + SHA_ENDUNG):
|
|
raise FileExistsError(pfad)
|
|
roh = (json.dumps(tafel, indent=1, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8") # pragma: no mutate
|
|
sha = hashlib.sha256(roh).hexdigest()
|
|
_atomar_neu(pfad, roh)
|
|
_atomar_neu(pfad + SHA_ENDUNG, ("%s %s\n" % (sha, os.path.basename(pfad))).encode("utf-8")) # pragma: no mutate
|
|
return sha
|
|
|
|
|
|
def lade(pfad):
|
|
"""Reads a table and checks it against its .sha256; ValueError on a mismatch."""
|
|
with open(pfad, "rb") as f:
|
|
roh = f.read()
|
|
with open(pfad + SHA_ENDUNG, encoding="utf-8") as f: # pragma: no mutate
|
|
soll = f.read().split()[0]
|
|
if hashlib.sha256(roh).hexdigest() != soll:
|
|
raise ValueError("SHA256 of %s does not match its .sha256" % pfad) # pragma: no mutate
|
|
return json.loads(roh)
|