diff --git a/messung/motor/fbl1/knoten.py b/messung/motor/fbl1/knoten.py index e5c8ea04..26f8a959 100644 --- a/messung/motor/fbl1/knoten.py +++ b/messung/motor/fbl1/knoten.py @@ -3,6 +3,7 @@ # Je Knoten: Topf vor dem River (Chips), Stärke Bot/Gegner (motor staerke), Gegnerzug (0 Check, 1 Einsatz), Einsatz/Topf, # Antwort des Bots (0 Fold, 1 Call, 2 Raise; -1 ohne Einsatz), Handnummer (Hälfte A/B nach Parität). import sys; sys.dont_write_bytecode = True +import os; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import json, os, subprocess import numpy as np Q = "D:/Projects/pokerfreak-daten/zenodo-tafeln/acpc/npy_2017" @@ -37,8 +38,10 @@ def main(): r = subprocess.run([EXE, "staerke"], input=txt, capture_output=True, text=True, creationflags=0x4000) hs = np.array([float(x) for x in r.stdout.split()]).reshape(-1, 2) os.makedirs(os.path.dirname(aus), exist_ok=True) - np.savez(aus, hand=np.asarray(L["hand"])[J], datei=np.asarray(L["datei"])[J], topf=np.array([z[1] for z in zeilen]), hs_bot=hs[:, 0], hs_geg=hs[:, 1], + SI.warte_platz(aus); tmp = aus + ".tmp%d.npz" % os.getpid() # temp-then-rename (Regel 28.11.) + np.savez(tmp, hand=np.asarray(L["hand"])[J], datei=np.asarray(L["datei"])[J], topf=np.array([z[1] for z in zeilen]), hs_bot=hs[:, 0], hs_geg=hs[:, 1], zug=np.array([z[2] for z in zeilen]), anteil=np.array([z[3] for z in zeilen]), antwort=np.array([z[4] for z in zeilen])) + os.replace(tmp, aus) z = np.array([z[2] for z in zeilen]); a = np.array([z[4] for z in zeilen]) print("gespeichert", aus, "Einsatz", int(z.sum()), "Fold", int((a == 0).sum()), "Call", int((a == 1).sum()), "Raise", int((a == 2).sum())) diff --git a/messung/motor/fbl1/lernkurve.py b/messung/motor/fbl1/lernkurve.py index 519a2410..36d326c8 100644 --- a/messung/motor/fbl1/lernkurve.py +++ b/messung/motor/fbl1/lernkurve.py @@ -2,6 +2,7 @@ # Dazu: Abstand der aus N Knoten geschaetzten Bot-Strategie (Weitergehen je Groesse und Fach, nur sichtbar: Aktionen + Showdown nach # Call) zur Strategie aus Haelfte B. python -X utf8 messung/motor/fbl1/lernkurve.py -> lernkurve.json import sys; sys.dont_write_bytecode = True +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import json, os import numpy as np HIER = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HIER) @@ -16,4 +17,4 @@ for N in (1000, 10000, 100000, int(A.sum())): sA = L.echt(TA); gew = TB["n_js"]; fehler = float((np.abs(sA - sB) * gew).sum() / gew.sum()) z = {"N": N, "einsaetze": int(sum(n for _, n in TA["fold"])), "fehler_weiter_L1": round(fehler, 4), **{k: round(v, 4) for k, v in r.items() if not k.startswith("pi_")}} out.append(z); print(json.dumps(z), flush=True) -json.dump(out, open(os.path.join(HIER, "lernkurve.json"), "w", encoding="utf-8"), indent=1) +SI.json_ersetzen(os.path.join(HIER, "lernkurve.json"), out, indent=1) diff --git a/messung/motor/fbl1/loeser.py b/messung/motor/fbl1/loeser.py index 60a26c20..cd92995e 100644 --- a/messung/motor/fbl1/loeser.py +++ b/messung/motor/fbl1/loeser.py @@ -5,6 +5,7 @@ # Loeser: Regret-Matching+ fuer uns gegen die (eingeschraenkte) beste Antwort des Bots; Wert V = schlimmste vertraegliche # Verteilung gegen unsere Durchschnittsstrategie (exakt, gierig), G = gegen die echte Bot-Strategie aus Haelfte B. import sys; sys.dont_write_bytecode = True +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import json, math, os import numpy as np HIER = os.path.dirname(os.path.abspath(__file__)) @@ -165,7 +166,7 @@ def main(): for k in reihe[0]: xs = np.sort([x[k] for x in reihe]); out.setdefault("ci95", {})[k] = [float(np.quantile(xs, .025)), float(np.quantile(xs, .975))] print("ci95", json.dumps(out["ci95"])) - json.dump(out, open(os.path.join(HIER, "ergebnis_decke.json" if nur else "ergebnis.json"), "w", encoding="utf-8"), indent=1) + SI.json_ersetzen(os.path.join(HIER, "ergebnis_decke.json" if nur else "ergebnis.json"), out, indent=1) if __name__ == "__main__": diff --git a/messung/motor/fbl2/decke.py b/messung/motor/fbl2/decke.py index 137056d5..edb39e43 100644 --- a/messung/motor/fbl2/decke.py +++ b/messung/motor/fbl2/decke.py @@ -4,6 +4,7 @@ import sys; sys.dont_write_bytecode = True import collections, json, os import numpy as np +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI HIER = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, os.path.join(HIER, "..", "riverbr")) import richter as RI RB = RI.RB @@ -33,7 +34,7 @@ def main(): "riverbr_bb100": 7.77, "decke_minus_riverbr": round(float(m) - 7.77, 2), "gegen_klein_le_0_4": {"n": klein[0], "bb100": round(100 * klein[1] / N, 2)}, "zuege": {k: [n, round(100 * w / N, 2)] for k, (n, w) in sorted(zug.items(), key=lambda t: -t[1][1]) if k.split(">")[0] != k.split(">")[1]}} - json.dump(out, open(os.path.join(HIER, "decke.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False); print(json.dumps(out, ensure_ascii=False, indent=1)) + SI.json_ersetzen(os.path.join(HIER, "decke.json"), out, indent=1, ensure_ascii=False); print(json.dumps(out, ensure_ascii=False, indent=1)) if __name__ == "__main__": diff --git a/messung/motor/fbl2/fbl.py b/messung/motor/fbl2/fbl.py index 5d9aac79..fd75d305 100644 --- a/messung/motor/fbl2/fbl.py +++ b/messung/motor/fbl2/fbl.py @@ -6,6 +6,7 @@ import sys; sys.dont_write_bytecode = True import collections, json, os import numpy as np +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI HIER = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, os.path.join(HIER, "..", "riverbr")) import richter as RI RB = RI.RB @@ -206,7 +207,7 @@ def main(): x = json.loads(z); v = x["richter"]; rb[x["i"]] = (v[1] - v[0]) if None not in v else 0.0 byh_f, byh_rb = collections.defaultdict(float), collections.defaultdict(float) st = collections.Counter(); zug = collections.defaultdict(lambda: [0, 0.0]); klein = [0, 0, 0.0, 0.0] - with open(os.path.join(HIER, "fbl.jsonl"), "w", encoding="utf-8", newline="\n") as aus: + with SI.Zeilen(os.path.join(HIER, "fbl.jsonl")) as aus: for i, f in enumerate(F): st["entscheidungen"] += 1; byh_rb[f["hk"]] += rb.get(i, 0.0); byh_f[f["hk"]] += 0.0 opt, mb = RI.motor_option(f); am, Bm = RI.option_betrag(f, opt, mb) @@ -254,7 +255,7 @@ def main(): "gegen_klein_le_0_4": {"n": klein[0], "geaendert": klein[1], "fbl_bb100": round(100 * klein[3] / N, 2), "riverbr_bb100": round(100 * klein[2] / N, 2)}, "zuege": {k: [n, round(100 * w / N, 2)] for k, (n, w) in sorted(zug.items(), key=lambda t: -t[1][0])}, "fold_gegen_uns": "riverbr/fold_probe.json: 0,576 gegen uns vs 0,55 Pool-Erwartung (n 505), nicht klar darunter"} - json.dump(out, open(os.path.join(HIER, "fbl.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False); print(json.dumps(out, ensure_ascii=False, indent=1)) + SI.json_ersetzen(os.path.join(HIER, "fbl.json"), out, indent=1, ensure_ascii=False); print(json.dumps(out, ensure_ascii=False, indent=1)) if __name__ == "__main__": diff --git a/messung/motor/riverbr/batterie_tor.py b/messung/motor/riverbr/batterie_tor.py index 62cbbc23..a44f070c 100644 --- a/messung/motor/riverbr/batterie_tor.py +++ b/messung/motor/riverbr/batterie_tor.py @@ -2,6 +2,7 @@ # Fehlerbalken wie messung/batterie/auswertung.py (Cluster = Blatt). Kopfzahl = schlechtester Typ. # python -X utf8 messung/motor/riverbr/batterie_tor.py -> batterie_tor.json import sys; sys.dont_write_bytecode = True +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import collections, glob, json, math, os HIER = os.path.dirname(os.path.abspath(__file__)) K = "motor@RIVERBR=1" @@ -44,7 +45,7 @@ def main(): out["schlechtester_typ_motor"] = wm; out["schlechtester_typ_kandidat"] = wk out["kopf_motor"] = T[wm]["motor"]; out["kopf_kandidat"] = T[wk][K] out["tor_b"] = nicht_unter(wm, 0) and nicht_unter(wk, 0) and all(nicht_unter(t, -2) for t in T) - json.dump(out, open(os.path.join(HIER, "batterie_tor.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) + SI.json_ersetzen(os.path.join(HIER, "batterie_tor.json"), out, indent=1, ensure_ascii=False) print("%-10s %22s %22s %22s %6s" % ("typ", "motor", "kandidat", "kand-motor", "anders")) for t, r in out["typen"].items(): f = lambda x: "%+8.2f ±%6.2f (%d)" % tuple(x) if x else "-" diff --git a/messung/motor/riverbr/fold_probe.py b/messung/motor/riverbr/fold_probe.py index dc428d3a..07f62e35 100644 --- a/messung/motor/riverbr/fold_probe.py +++ b/messung/motor/riverbr/fold_probe.py @@ -2,6 +2,7 @@ # gegen die Pool-Quote derselben Schicht (Zelle x OOP/IP x Groesse) aus hhDealer (fluss.npz). Nur Zaehlung. # python -X utf8 messung/motor/riverbr/fold_probe.py -> fold_probe.json import sys; sys.dont_write_bytecode = True +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import collections, json, math, os, pickle import numpy as np @@ -110,7 +111,7 @@ def main(): for e in E: zellen[" ".join(e["zl"])].append(e) for k, xs in sorted(zellen.items(), key=lambda x: -len(x[1])): out["je_zelle"][k] = stat(xs) out["pool_faelle"] = sum(v for k, v in C.items() if k[0] is None) - json.dump(out, open(os.path.join(HIER, "fold_probe.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) + SI.json_ersetzen(os.path.join(HIER, "fold_probe.json"), out, indent=1, ensure_ascii=False) print(json.dumps({k: out[k] for k in ("gesamt", "je_groesse", "je_lage")}, ensure_ascii=False, indent=1)) for k, v in out["je_zelle"].items(): print(k, v) diff --git a/messung/motor/riverbr/richter.py b/messung/motor/riverbr/richter.py index 84273c92..4fa71a7b 100644 --- a/messung/motor/riverbr/richter.py +++ b/messung/motor/riverbr/richter.py @@ -5,6 +5,7 @@ import sys; sys.dont_write_bytecode = True import bisect, collections, json, math, os, random import numpy as np +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI HIER = os.path.dirname(os.path.abspath(__file__)); HAUPT = "D:/Projects/pokerfreak" OG = HAUPT + "/messung/orakel/obergrenze" @@ -239,7 +240,7 @@ def main(): ZELLEN = {RB.Z.schluessel(r["zelle"]) for r in G2 if r["traegt"] and r["v1"][0] >= .5 and r["v2"][0] >= .5} - RAUS print("Zellen", len(ZELLEN), flush=True) zl = []; st = collections.Counter() - with open(os.path.join(HIER, "kandidat.jsonl"), "w", encoding="utf-8", newline="\n") as aus: + with SI.Zeilen(os.path.join(HIER, "kandidat.jsonl")) as aus: for i, f in enumerate(F): opt, mb = motor_option(f); extra = ("motor", mb) if opt == "motor" else None Rg = M0.range(f["k"]) @@ -292,7 +293,7 @@ def main(): "tor_a": bool(ges[1] > 0 and st["geaendert_unbepreist"] < 0.05 * max(st["geaendert"], 1)), "zuege": {k: [n, zuege_wert[k]] for k, n in zuege.most_common()}, "je_zelle": zellen_out} out["m0"] = "river_br.Modell (Tafel wird veraendert, erster Lauf)" if os.environ.get("RIVERBR_ALT_FEHLER") else "ohne Tafel-Veraenderung" - json.dump(out, open(os.path.join(HIER, "richter.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False) + SI.json_ersetzen(os.path.join(HIER, "richter.json"), out, indent=1, ensure_ascii=False) print(json.dumps(out, ensure_ascii=False, indent=1)) diff --git a/messung/motor/riverbr/rueck.py b/messung/motor/riverbr/rueck.py index 0b59e07a..f902e3e6 100644 --- a/messung/motor/riverbr/rueck.py +++ b/messung/motor/riverbr/rueck.py @@ -7,6 +7,7 @@ # RUECK_TEIL=i/n: nur jede n-te Anfrage ab i (parallele Teile), Dateien mit Endung -i. Ohne Vergleichs-Exe nur der Kandidat. # RUECK_GLEICH=n mit Vergleichs-Exe: nur Gleichheit ohne Schalter an jeder n-ten Anfrage (Endung -gleich). import sys; sys.dont_write_bytecode = True +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import collections, json, os, queue, random, subprocess, threading HIER = os.path.dirname(os.path.abspath(__file__)); HAUPT = "D:/Projects/pokerfreak" sys.path[:0] = [HIER, HAUPT + "/messung/pruef"] @@ -92,7 +93,7 @@ def main(): K = None if nur_gleich else starte(exe, {"MOTOR_RIVERBR": "1"}) V = starte(vergleich, {}) if vergleich else None O = starte(exe, {}) if vergleich else None - C = collections.Counter(); aus = open(os.path.join(HIER, "rueck_abweichungen%s.jsonl" % sfx), "w", encoding="utf-8", newline="\n") + C = collections.Counter(); aus = open(os.path.join(HIER, "rueck_abweichungen%s.jsonl" % sfx), "a", encoding="utf-8") for i, q in enumerate(qs): q = dict(q, seed=q.get("seed", 3)) C["anfragen"] += 1; C[q["street"]] += 1 @@ -122,7 +123,7 @@ def main(): if i % 100 == 0: print(i, dict(C), flush=True) out = {"karte": "KARTE.md", "exe": os.path.basename(exe), "vergleich": vergleich and os.path.basename(vergleich), **dict(C), "tor_c_teil": C["unzulaessig"] == 0 and C["fehler_antwort"] == 0 and C["ohne_schalter_ungleich"] == 0} - json.dump(out, open(os.path.join(HIER, "rueck%s.json" % sfx), "w", encoding="utf-8"), indent=1, ensure_ascii=False) + SI.json_ersetzen(os.path.join(HIER, "rueck%s.json" % sfx), out, indent=1, ensure_ascii=False) print("FERTIG", json.dumps(out, ensure_ascii=False)) for m in (K, V, O): if m: m[0].kill() diff --git a/messung/motor/riverbr_c/exakt.py b/messung/motor/riverbr_c/exakt.py index 9d485b6c..cfdb5a26 100644 --- a/messung/motor/riverbr_c/exakt.py +++ b/messung/motor/riverbr_c/exakt.py @@ -7,6 +7,7 @@ # E[neu] - E[alt] = Mittel ueber Salz 0..K; ungekippte Haende tragen 0. Intervall ueber Blaetter wie lauf.py. import sys; sys.dont_write_bytecode = True import json, math, os, random, subprocess +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI HIER = os.path.dirname(os.path.abspath(__file__)); W = os.path.normpath(os.path.join(HIER, "..", "..", "..")) sys.path[:0] = [os.path.join(W, "messung", "pruef")] os.environ.setdefault("TISCH_DATEN", "D:/Projects/pokerfreak/daten/grundstrategie/motor") @@ -89,9 +90,12 @@ def main(): for z in open(pfad, encoding="utf-8"): try: y = json.loads(z); fertig[(y["b"], y["platz"])] = y except ValueError: pass - aus = open(pfad, "w", encoding="utf-8") - for y in fertig.values(): aus.write(json.dumps(y) + chr(10)) - aus.flush() + if os.path.exists(pfad) and os.path.getsize(pfad) > 0: # nur anhaengen; abgeschnittene letzte Zeile erst abschliessen + with open(pfad, "rb") as t: t.seek(-1, 2); offen = t.read(1) != b"\n" + if offen: + SI.warte_platz(pfad) + with open(pfad, "a", encoding="utf-8") as t: t.write(chr(10)) + aus = open(pfad, "a", encoding="utf-8") treffer = gesamt = 0; summe = {} for b in sorted(voll): summe[b] = 0.0 @@ -110,6 +114,7 @@ def main(): d = [u - v for u, v in zip(neu, alt)]; m = sum(d) / len(d) se = math.sqrt(sum((y - m) ** 2 for y in d) / (len(d) - 1) / len(d)) summe[b] += m + SI.warte_platz(pfad) aus.write(json.dumps({"b": b, "platz": x["platz"], "ok": ok, "stichprobe": x["neu"] - x["alt"], "exakt": m, "se_mc": se, "e_neu": sum(neu) / len(neu), "e_alt": sum(alt) / len(alt), "r": x["r"]}) + "\n"); aus.flush() cache.clear() @@ -117,7 +122,7 @@ def main(): h = 1.96 * math.sqrt(sum((v - m) ** 2 for v in w) / (n - 1) / n) r = {"lauf": lauf, "art": art, "K": K, "blaetter": n, "haende": 6 * n, "bb100": m, "lo": m - h, "hi": m + h, "halb": h, "gekippt": gesamt, "nachgespielt_gleich": treffer} - json.dump(r, open(os.path.join(HIER, lauf + ".exakt.json"), "w", encoding="utf-8"), indent=1); print("ERGEBNIS", json.dumps(r), flush=True) + SI.json_ersetzen(os.path.join(HIER, lauf + ".exakt.json"), r, indent=1); print("ERGEBNIS", json.dumps(r), flush=True) if __name__ == "__main__": diff --git a/messung/motor/riverbr_c/exakt_kette.sh b/messung/motor/riverbr_c/exakt_kette.sh index 8c058b99..d7df3128 100644 --- a/messung/motor/riverbr_c/exakt_kette.sh +++ b/messung/motor/riverbr_c/exakt_kette.sh @@ -7,7 +7,7 @@ ram() { powershell -NoProfile -c "[int]((Get-CimInstance Win32_OperatingSystem). warte() { until [ "$(platz)" -ge 3 ] && [ "$(ram)" -ge "$1" ]; do sleep 120; done; } export TISCH_FAEDEN=2 warte 30; python -X utf8 $R/exakt.py d_holdout d 32 >> $R/d_exakt.log 2>&1 -warte 30; TISCH_GEGNER=motor python -X utf8 $R/exakt.py e1_motor e 32 > $R/e1_exakt.log 2>&1 +warte 30; TISCH_GEGNER=motor python -X utf8 $R/exakt.py e1_motor e 32 >> $R/e1_exakt.log 2>&1 F=D:/pokerfreak-fremd/sharingan; H=$(pwd -W)/messung/pruef -warte 43; TISCH_FAEDEN=1 TISCH_GEGNER="py:$H/sh6.py $F/code/target/serve/pokerbench-pruef6-sharingan.exe $F/weights/B-local-2e10.plcp $F/data/buckets-200 local --no-search" python -X utf8 $R/exakt.py e2_sharingan e 32 > $R/e2_exakt.log 2>&1 +warte 43; TISCH_FAEDEN=1 TISCH_GEGNER="py:$H/sh6.py $F/code/target/serve/pokerbench-pruef6-sharingan.exe $F/weights/B-local-2e10.plcp $F/data/buckets-200 local --no-search" python -X utf8 $R/exakt.py e2_sharingan e 32 >> $R/e2_exakt.log 2>&1 echo KETTE_FERTIG diff --git a/messung/motor/riverbr_c/lauf.py b/messung/motor/riverbr_c/lauf.py index e996eef4..8fa222b7 100644 --- a/messung/motor/riverbr_c/lauf.py +++ b/messung/motor/riverbr_c/lauf.py @@ -2,6 +2,7 @@ # python -X utf8 messung/motor/riverbr_c/lauf.py d|e (Gegner fuer e: TISCH_GEGNER=motor | py:) # Startet tisch6_pool (MOTOR_RIVERBR=1, TISCH_VERGLEICH=riverbr) erst, wenn genug Speicher frei ist (>= 20 GB bleiben), wertet alle 60 s aus und beendet den Lauf, sobald entschieden. Ergebnis: .ergebnis.json; Rohzeilen .jsonl. import sys; sys.dont_write_bytecode = True +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")); import sicher as SI import json, math, os, subprocess, time HIER = os.path.dirname(os.path.abspath(__file__)); W = os.path.normpath(os.path.join(HIER, "..", "..", "..")) MIN, TAKT = 100, 60 @@ -68,7 +69,7 @@ def main(): s = stand(pfad) if u == "max erreicht" and "lo" in s: u = urteil(dict(s, halb=0.0), art) or u s["urteil"] = u; s["art"] = art - json.dump(s, open(os.path.join(HIER, name + ".ergebnis.json"), "w", encoding="utf-8"), indent=1); print("ERGEBNIS", json.dumps(s), flush=True) + SI.json_ersetzen(os.path.join(HIER, name + ".ergebnis.json"), s, indent=1); print("ERGEBNIS", json.dumps(s), flush=True) if __name__ == "__main__": diff --git a/messung/motor/sicher.py b/messung/motor/sicher.py new file mode 100644 index 00000000..bc719508 --- /dev/null +++ b/messung/motor/sicher.py @@ -0,0 +1,54 @@ +# Ergebnisdateien sicher schreiben (Regel Owner 28.11., CLAUDE.md): nie ueberschreiben oder leeren; anhaengen oder +# temp-then-rename; ein Lauf, der eine nicht leere Datei leeren wuerde, bricht ab; unter 3 GB frei auf dem Laufwerk pausiert alles. +import json, os, shutil, sys, time + +MIN_FREI = 3 * 1024 ** 3 + + +def frei(pfad): + d = os.path.dirname(os.path.abspath(pfad)) or "." + return shutil.disk_usage(d).free + + +def warte_platz(pfad, takt=60): + """pausiert, solange unter 3 GB frei sind (nie schreiben, nie abbrechen)""" + gemeldet = False + while frei(pfad) < MIN_FREI: + if not gemeldet: print("PAUSE: unter 3 GB frei fuer", pfad, file=sys.stderr, flush=True); gemeldet = True + time.sleep(takt) + + +def ersetzen(pfad, text): + """temp-then-rename; leerer Inhalt ueber einer nicht leeren Datei bricht ab""" + if not text.strip() and os.path.exists(pfad) and os.path.getsize(pfad) > 0: + raise SystemExit("ABBRUCH: wuerde nicht leere Datei leeren: " + pfad) + warte_platz(pfad) + tmp = pfad + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8", newline="\n") as f: + f.write(text); f.flush(); os.fsync(f.fileno()) + os.replace(tmp, pfad) + + +def json_ersetzen(pfad, obj, **kw): + ersetzen(pfad, json.dumps(obj, **kw)) + + +class Zeilen: + """JSONL-Ergebnis eines Laufs: sammelt in .tmp (Zeile fuer Zeile, mit Platzpause), am Ende ersetzen(). + Bricht der Lauf ab, bleibt die alte Datei unberuehrt.""" + def __init__(self, pfad): + self.pfad = pfad; self.tmp = pfad + ".tmp%d" % os.getpid(); warte_platz(pfad) + self.f = open(self.tmp, "w", encoding="utf-8", newline="\n"); self.n = 0 + + def write(self, s): + if self.n % 100 == 0: warte_platz(self.pfad) + self.f.write(s); self.n += 1 + + def __enter__(self): return self + + def __exit__(self, art, *_): + self.f.flush(); os.fsync(self.f.fileno()); self.f.close() + if art is not None: return False # Fehler: alte Datei bleibt, tmp liegt daneben + if os.path.getsize(self.tmp) == 0 and os.path.exists(self.pfad) and os.path.getsize(self.pfad) > 0: + os.remove(self.tmp); raise SystemExit("ABBRUCH: wuerde nicht leere Datei leeren: " + self.pfad) + os.replace(self.tmp, self.pfad) diff --git a/messung/pruef/tisch6_pool.py b/messung/pruef/tisch6_pool.py index 717d8e7a..46b9468a 100644 --- a/messung/pruef/tisch6_pool.py +++ b/messung/pruef/tisch6_pool.py @@ -9,6 +9,7 @@ import os import random import subprocess import sys +import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "../motor")); import sicher as SI import pool_gegner as G import tisch6 as T @@ -103,7 +104,7 @@ with open(aus, "a", encoding="utf-8") as f: z["alt"], z["r"] = round(erg[platz] / 100, 4), list(regeln) if arm == "stat": z = {"s": g, "h": [(e["street"][0], e["seat"] - 1, e["action"]) for e in hist]} - f.write(json.dumps(z) + "\n") + SI.warte_platz(aus); f.write(json.dumps(z) + "\n") break - f.write(json.dumps(z, separators=(",", ":")) + "\n") + SI.warte_platz(aus); f.write(json.dumps(z, separators=(",", ":")) + "\n") f.flush()