From 85b87d8d6361a8ce1f2f43eebe2becdea26fdb8d Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 06:57:51 +0100 Subject: [PATCH 1/6] Flop-Bibliothek nachschlagen: vierte Topfart Limp-Raise (SB limpt, BB erhoeht, SB bezahlt: limpraise/BBxSB), Groessen-Vergleich (flopbib --groesse-vergleich), Farm-Bau und Farm-Treiber fuer Windows Co-Authored-By: Claude Opus 5.5 --- entscheiden/motor/src/flopbib.rs | 91 ++++++++++++++++++++++ entscheiden/motor/src/flopbib_nach.rs | 26 ++++++- messung/motor/flopbib/farm/bau-flopbib.ps1 | 32 ++++++++ messung/motor/flopbib/farm/flopbib_farm.py | 46 +++++++++++ 4 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 messung/motor/flopbib/farm/bau-flopbib.ps1 create mode 100644 messung/motor/flopbib/farm/flopbib_farm.py diff --git a/entscheiden/motor/src/flopbib.rs b/entscheiden/motor/src/flopbib.rs index 053a91cc..318f811c 100644 --- a/entscheiden/motor/src/flopbib.rs +++ b/entscheiden/motor/src/flopbib.rs @@ -395,7 +395,98 @@ fn lage_vergleich(a: &[String]) -> Result<(), String> { Ok(()) } +/// Reichweite des Spielers `p` am Knoten `weg` aus der Strategie entlang des Wegs (ohne den Boden von `weights()` dieser Loeser-Kopie). +fn reichweite_weg(g: &mut PostFlopGame, weg: &[usize], p: usize) -> Vec { + g.back_to_root(); + let mut w = g.weights(p).to_vec(); + for (i, &z) in weg.iter().enumerate() { + g.apply_history(&weg[..i]); + if g.current_player() == p { + let (st, n) = (g.strategy(), w.len()); + (0..n).for_each(|h| w[h] *= st[z * n + h]); + } + } + g.apply_history(weg); + w +} + +/// `motor flopbib --groesse-vergleich `: der Gegner setzt x Topf (oop: OOP setzt an der Wurzel, IP +/// antwortet; ip: OOP checkt, IP setzt, OOP antwortet). Echte Lage = Live-Menue plus dieser Einsatz (wie Flop exakt), geloest; Bibliothek = +/// Live-Menue, Antwort am Knoten nach dem Bibliothekseinsatz (Abbildung auf den naechsten Einsatz). Verlust unserer Antwort-Mischung in % Topf. +fn groesse_vergleich(a: &[String]) -> Result<(), String> { + let (datei, linie, flop_s, x_s, wer) = (a.first().ok_or("lagen")?, a.get(1).ok_or("linie")?, a.get(2).ok_or("flop")?, a.get(3).ok_or("x")?, a.get(4).ok_or("oop|ip")?); + let flop = flop_lesen(flop_s).ok_or("Flop unlesbar")?; + let x: f64 = x_s.parse().map_err(|_| "x")?; + let ziel: f32 = std::env::var("FLOPBIB_ZIEL").map_err(|_| "FLOPBIB_ZIEL fehlt")?.parse::().map_err(|_| "FLOPBIB_ZIEL")? / 100.0; + let v = lage(datei, linie)?; + let (ab, mut gb) = geloest(&v, flop, ziel)?; + let auf = aufgabe(&v, flop)?; + let einsatz = (x * auf.pot as f64).round() as i32; + let (setzer, vorher): (usize, Vec) = match wer.as_str() { + "oop" => (0, vec![]), + "ip" => (1, vec![nachrechnen::Zug2 { p: 0, art: 1, ziel: 0 }]), + _ => return Err("oop|ip".into()), + }; + let mut verlauf = vorher.clone(); + verlauf.push(nachrechnen::Zug2 { p: setzer, art: 2, ziel: einsatz }); + let mut ge = nachrechnen::bau_mit(&auf, &[verlauf.clone()], true)?; + crate::flop_exakt::loese_bis(&ge, auf.pot, ziel, Instant::now() + Duration::from_secs(3 * 3600)); + postflop_solver::finalize(&mut ge); + // Weg in der echten Lage: vorher (Check = Zug 0) und der Einsatz + let mut weg_e: Vec = vorher.iter().map(|_| 0usize).collect(); + ge.apply_history(&weg_e); + let i = ge.available_actions().iter().position(|a| matches!(a, postflop_solver::Action::Bet(b) if (*b - einsatz).abs() <= 1)).ok_or("Einsatz fehlt im Baum")?; + weg_e.push(i); + // Weg in der Bibliothek: naechster Einsatz + let mut weg_b: Vec = vorher.iter().map(|_| 0usize).collect(); + gb.apply_history(&weg_b); + let bz = gb.available_actions(); + let j = bz + .iter() + .enumerate() + .filter_map(|(j, a)| match a { + postflop_solver::Action::Bet(b) | postflop_solver::Action::AllIn(b) => Some((j, (*b as f64 - einsatz as f64).abs())), + _ => None, + }) + .min_by(|p, q| p.1.total_cmp(&q.1)) + .map(|p| p.0) + .ok_or("kein Einsatz in der Bibliothek")?; + weg_b.push(j); + let wir = 1 - setzer; + let w = reichweite_weg(&mut ge, &weg_e, wir); + gb.apply_history(&weg_b); + ge.apply_history(&weg_e); + let skala = 1.0; + let karte = zuege_abbilden(&gb.available_actions(), &ge.available_actions(), skala).ok_or("Zug nicht abbildbar")?; + ge.cache_normalized_weights(); + let (q, s_echt) = (ge.expected_values_detail(wir), ge.strategy()); + let (he, hb) = (ge.private_cards(wir).to_vec(), gb.private_cards(wir).to_vec()); + let (n, nb, zb) = (he.len(), hb.len(), gb.available_actions().len()); + let sb_roh = gb.strategy(); + let mut s_bib = vec![0.0f32; s_echt.len()]; + let mut w2 = w.clone(); + for (h, k) in he.iter().enumerate() { + match hb.iter().position(|y| y == k) { + Some(i) => (0..zb).for_each(|z| s_bib[karte[z] * n + h] += sb_roh[z * nb + i]), + None => w2[h] = 0.0, + } + } + let verl = verlust(&s_bib, &s_echt, &q, &w2, n); + let l = |g: &PostFlopGame, p: i32| postflop_solver::compute_exploitability(g) / p as f32 * 100.0; + println!("{}", json!({"linie": linie, "flop": flop_s, "x": x, "wer_setzt": wer, "einsatz": einsatz, "bib_zug": format!("{:?}", bz[j]), + "verlust_topf_prozent": verl / auf.pot as f64 * 100.0, "luecke_prozent": [l(&gb, ab.pot), l(&ge, auf.pot)], + "zuege_bib": gb.available_actions().iter().map(|x| format!("{x:?}")).collect::>(), "zuege_echt": ge.available_actions().iter().map(|x| format!("{x:?}")).collect::>()})); + Ok(()) +} + pub fn lauf(a: &[String]) { + if a.first().map(String::as_str) == Some("--groesse-vergleich") { + if let Err(e) = groesse_vergleich(&a[1..]) { + eprintln!("flopbib: {e}"); + std::process::exit(2); + } + return; + } if a.first().map(String::as_str) == Some("--lade-messung") { match a.get(1).ok_or("Wurzel".to_string()).and_then(|w| crate::flopbib_nach::lade_messung(w)) { Ok(v) => println!("{v}"), diff --git a/entscheiden/motor/src/flopbib_nach.rs b/entscheiden/motor/src/flopbib_nach.rs index d13f0c75..f26ab4d3 100644 --- a/entscheiden/motor/src/flopbib_nach.rs +++ b/entscheiden/motor/src/flopbib_nach.rs @@ -36,6 +36,8 @@ pub const TOLERANZ_SRP: Toleranz = Toleranz { topf: (0.80, 1.364), spr: (0.189, pub const TOLERANZ_3BET: Toleranz = Toleranz { topf: (0.524, 1.270), spr: (0.389, 2.015), deckel: (0.6, 1.0) }; /// Limp-Topf: Topf (SB komplettiert) und Kappe stehen fest; nur Rundung. Deckel 6 bb statt 10 bb gemessen (SB-BB, 3 Flops): Verlust 0,000 %. pub const TOLERANZ_LIMP: Toleranz = Toleranz { topf: (0.99, 1.01), spr: (0.99, 1.01), deckel: (0.6, 1.0) }; +/// Limp-Raise: noch nicht vermessen, darum nur Rundung (die Lage der Bibliothek: Erhoehung auf 4 bb, Median der echten Haende). +pub const TOLERANZ_LIMPRAISE: Toleranz = Toleranz { topf: (0.99, 1.01), spr: (0.99, 1.01), deckel: (1.0, 1.0) }; /// Heads-up-Tisch (HU-Tafel hu100): Topf und SPR wie die Topfart (am 6-max gemessen, uebertragen); Rake-Deckel NL2 2,5 bb, NL5 2,6 bb - /// `HU_DECKEL` aus dem Lage-Vergleich der 2,5-bb-Loesung in der 2,6-bb-Lage. /// Gemessen (SRP, Limp, 3-Bet, je 3 Flops): Verlust der 2,5-bb-Loesung in der 2,6-bb-Lage hoechstens 0,010 % Topf. @@ -181,6 +183,8 @@ pub enum Topfart { Srp, Dreibet, Limp, + /// SB limpt, BB erhoeht, SB bezahlt (Linie `BBxSB`; die Tafel ist dort trainiert, andere Limp-Raise-Paare nicht geprueft) + LimpRaise, } /// Wie weit Topf (relativ) und Stack-Topf-Verhaeltnis (relativ) der echten Lage von der Kopfzeile abweichen duerfen. Hergeleitet aus dem @@ -208,6 +212,7 @@ impl Topfart { Topfart::Srp => "srp", Topfart::Dreibet => "3bet", Topfart::Limp => "limp", + Topfart::LimpRaise => "limpraise", } } @@ -227,6 +232,7 @@ impl Topfart { Topfart::Srp => TOLERANZ_SRP, Topfart::Dreibet => TOLERANZ_3BET, Topfart::Limp => TOLERANZ_LIMP, + Topfart::LimpRaise => TOLERANZ_LIMPRAISE, } } } @@ -253,6 +259,16 @@ pub fn lage_art(oop: usize, ip: usize, vorflop: &[(usize, u8)]) -> Result<(Topfa Ok((Topfart::Limp, "SB-BB".into())) } [e] => { + if vorflop[e].0 == spaet && vorflop[..e].iter().any(|z| z.0 == frueh && z.1 == 1) { + // Limp-Raise: der Fruehere limpt, der Spaetere erhoeht, der Fruehere bezahlt; sonst niemand + if (frueh, spaet) != (0, 1) { + return Err(format!("Limp-Raise {}x{} nicht in der Bibliothek", NAMEN[spaet], NAMEN[frueh])); + } + if andere_zahlen(0) || !vorflop[e + 1..].iter().any(|z| z.0 == frueh && z.1 == 1) { + return Err("Limp-Raise mit weiteren Spielern oder ohne Call".into()); + } + return Ok((Topfart::LimpRaise, "BBxSB".into())); + } if vorflop[e].0 != frueh { return Err("kein Single-Raised-Pot (Erhoehung nicht vom Frueheren)".into()); } @@ -422,7 +438,7 @@ fn rss() -> u64 { pub fn lade_messung(wurzel: &str) -> Result { let vorher = rss(); let mut schluessel = Vec::new(); - for unter in ["srp", "3bet", "limp", "hu/srp", "hu/3bet", "hu/limp"] { + for unter in ["srp", "3bet", "limp", "limpraise", "hu/srp", "hu/3bet", "hu/limp", "hu/limpraise"] { let dir = format!("{wurzel}/{unter}/bilder"); let Ok(linien) = std::fs::read_dir(&dir) else { continue }; for l in linien.flatten() { @@ -551,8 +567,14 @@ mod spec { assert!(lage_art(0, 4, &[(2, 0), (3, 0), (4, 2), (5, 1), (0, 2), (1, 0), (4, 1), (5, 0)]).is_err()); // 4-Bet assert!(lage_art(0, 5, &[(2, 0), (3, 0), (4, 0), (5, 2), (0, 2), (1, 0), (5, 2), (0, 1)]).unwrap_err().contains("4-Bet")); + // Limp-Raise SB-BB: SB limpt, BB erhoeht, SB bezahlt + assert_eq!(lage_art(0, 1, &[(2, 0), (3, 0), (4, 0), (5, 0), (0, 1), (1, 2), (0, 1)]), Ok((Topfart::LimpRaise, "BBxSB".into()))); + // Limp-Raise BTN-BB: nicht in der Bibliothek + assert!(lage_art(1, 5, &[(2, 0), (3, 0), (4, 0), (5, 1), (0, 0), (1, 2), (5, 1)]).unwrap_err().contains("Limp-Raise BBxBTN")); + // Limp-Raise mit weiterem Limper + assert!(lage_art(0, 1, &[(2, 0), (3, 0), (4, 1), (5, 0), (0, 1), (1, 2), (4, 0), (0, 1)]).is_err()); // Ordner - assert_eq!((Topfart::Srp.ordner(), Topfart::Dreibet.ordner(), Topfart::Limp.ordner()), ("srp", "3bet", "limp")); + assert_eq!((Topfart::Srp.ordner(), Topfart::Dreibet.ordner(), Topfart::Limp.ordner(), Topfart::LimpRaise.ordner()), ("srp", "3bet", "limp", "limpraise")); } #[test] diff --git a/messung/motor/flopbib/farm/bau-flopbib.ps1 b/messung/motor/flopbib/farm/bau-flopbib.ps1 new file mode 100644 index 00000000..a12dd181 --- /dev/null +++ b/messung/motor/flopbib/farm/bau-flopbib.ps1 @@ -0,0 +1,32 @@ +# Farm-Auftrag exakt: Windows-Exe der Flop-Bibliothek aus dem Quell-Archiv (kein Netz). $args[0] = Kurz-SHA, $args[1] = Zweck (Name der Exe). +# Archiv D:\Projects\pf-flopbib-farm\flopbib-.tar (git archive des Stands); Loeserkopie je Stand aus postflop-solver-mess + loeser-temp.patch +# (wie pf-temperatur\bau-temperatur-rein-2.ps1). Ergebnis D:\Projects\pf-flopbib-farm\pokerbench-flopbib--.exe +$ErrorActionPreference = "Stop" +$sha = $args[0]; $zweck = $args[1] +$fremd = "D:\Projects\fremd" +$basis = "D:\Projects\pf-flopbib-farm" +$wt = "$basis\src-$sha" +if (-not (Test-Path $wt)) { New-Item -ItemType Directory $wt | Out-Null; tar -xf "$basis\flopbib-$sha.tar" -C $wt; if ($LASTEXITCODE -ne 0) { throw "tar fehlgeschlagen" } } +$temp = "$fremd\postflop-solver-temp-$sha" +$toml = "$wt\entscheiden\motor\Cargo.toml" +(Get-Content $toml) -replace 'postflop-solver-temp"', "postflop-solver-temp-$sha`"" | Set-Content $toml -Encoding utf8 +$patchexe = "C:\Program Files\Git\usr\bin\patch.exe" +if (-not (Test-Path $temp)) { + robocopy "$fremd\postflop-solver-mess" $temp /E /XD target .git /NFL /NDL /NJH /NJS | Out-Null + Push-Location $temp; & $patchexe -p1 --binary -i "$wt\entscheiden\motor\loeser-temp.patch"; $rc = $LASTEXITCODE; Pop-Location + if ($rc -ne 0) { throw "patch fehlgeschlagen" } + "Loeserkopie angelegt" +} else { + Push-Location $temp; & $patchexe -p1 --binary -R --dry-run -i "$wt\entscheiden\motor\loeser-temp.patch" | Out-Null; $rc = $LASTEXITCODE; Pop-Location + if ($rc -ne 0) { throw "vorhandene Loeserkopie passt nicht zum Patch von $sha" } + "Loeserkopie passt" +} +Push-Location "$wt\entscheiden\motor" +cargo build --release --locked -j 8 +$rc = $LASTEXITCODE; Pop-Location +if ($rc -ne 0) { throw "cargo build fehlgeschlagen" } +$ziel = "$basis\pokerbench-flopbib-$zweck-$sha.exe" +Copy-Item "$wt\entscheiden\motor\target\release\motor.exe" $ziel -Force +& $ziel flopbib --flops | Measure-Object -Line | % { "Iso-Flops: $($_.Lines)" } +"EXE $ziel" +"SHA256 " + (Get-FileHash $ziel -Algorithm SHA256).Hash diff --git a/messung/motor/flopbib/farm/flopbib_farm.py b/messung/motor/flopbib/farm/flopbib_farm.py new file mode 100644 index 00000000..b4449d2e --- /dev/null +++ b/messung/motor/flopbib/farm/flopbib_farm.py @@ -0,0 +1,46 @@ +"""Flop-Bibliothek auf der Windows-Farm (exakt, 05.12.): loest die Schluessel einer Liste und legt die Bilder UNGEPACKT direkt in den +Bibliotheksordner (//.bin), wie der Motor sie liest (MOTOR_FLOP_BIBLIOTHEK). Fertige Bilder werden uebersprungen +(Fortsetzen nach Anhalten/Abbruch); jedes Bild schreibt die Exe atomar (aus.tmp -> aus). Je Schluessel eine Zeile in /../fertig-.jsonl. + python -X utf8 flopbib_farm.py --exe E --lagen L --schluessel S --ziel D:\\...\\flopbib-v2\\srp\\bilder --name N [--parallel 3] [--faeden 8] + [--menue eng|breit] [--zielluecke 1.0] +Die Schlange setzt die Prioritaet (BelowNormal) und haelt den Lauf an, solange der Laeufer spielt.""" +import argparse, json, os, subprocess, time, concurrent.futures as cf + +ap = argparse.ArgumentParser() +for k in ("exe", "lagen", "schluessel", "ziel", "name"): + ap.add_argument("--" + k, required=True) +ap.add_argument("--parallel", type=int, default=3) +ap.add_argument("--faeden", type=int, default=8) +ap.add_argument("--menue", default=None) +ap.add_argument("--zielluecke", default="1.0") +a = ap.parse_args() +log = os.path.join(os.path.dirname(os.path.abspath(a.ziel)), f"fertig-{a.name}.jsonl") +keys = [z.split()[:2] for z in open(a.schluessel, encoding="utf-8") if z.strip()] +offen = [(l, f) for l, f in keys if not os.path.exists(os.path.join(a.ziel, l, f + ".bin"))] +print(f"{time.strftime('%H:%M:%S')} {len(keys)} Schluessel, {len(offen)} offen", flush=True) + + +def eins(k): + linie, flop = k + os.makedirs(os.path.join(a.ziel, linie), exist_ok=True) + aus = os.path.join(a.ziel, linie, flop + ".bin") + env = dict(os.environ, RAYON_NUM_THREADS=str(a.faeden), FLOPBIB_ZIEL=a.zielluecke) + if a.menue: + env["FLOPBIB_MENUE"] = a.menue + t = time.time() + r = subprocess.run([a.exe, "flopbib", a.lagen, linie, flop, aus], env=env, capture_output=True, text=True) + zeile = next((z for z in r.stdout.splitlines()[::-1] if z.startswith("{")), None) + d = json.loads(zeile) if (r.returncode == 0 and zeile) else {"linie": linie, "flop": flop, "fehler": f"rc {r.returncode}: {r.stderr[-300:]}"} + d["s"] = round(time.time() - t, 1) + with open(log, "a", encoding="utf-8") as f: + f.write(json.dumps(d) + "\n") + return d + + +n = 0 +with cf.ThreadPoolExecutor(a.parallel) as ex: + for d in ex.map(eins, offen): + n += 1 + if n % 50 == 0: + print(f"{time.strftime('%H:%M:%S')} {n}/{len(offen)}", flush=True) +print(f"{time.strftime('%H:%M:%S')} fertig {n}", flush=True) From c237e48c61b4e0878c053dd845c2f2fce40b98fd Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 06:58:11 +0100 Subject: [PATCH 2/6] Farm-Treiber: wartet auf die Exe (Bau als eigener Auftrag) Co-Authored-By: Claude Opus 5.5 --- messung/motor/flopbib/farm/flopbib_farm.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/messung/motor/flopbib/farm/flopbib_farm.py b/messung/motor/flopbib/farm/flopbib_farm.py index b4449d2e..015a42f8 100644 --- a/messung/motor/flopbib/farm/flopbib_farm.py +++ b/messung/motor/flopbib/farm/flopbib_farm.py @@ -13,7 +13,13 @@ ap.add_argument("--parallel", type=int, default=3) ap.add_argument("--faeden", type=int, default=8) ap.add_argument("--menue", default=None) ap.add_argument("--zielluecke", default="1.0") +ap.add_argument("--warte-stunden", type=float, default=6.0, help="so lange auf die Exe warten (Bau als eigener Auftrag)") a = ap.parse_args() +bis = time.time() + a.warte_stunden * 3600 +while not os.path.exists(a.exe): + if time.time() > bis: + raise SystemExit(f"Exe {a.exe} fehlt nach {a.warte_stunden} h") + time.sleep(30) log = os.path.join(os.path.dirname(os.path.abspath(a.ziel)), f"fertig-{a.name}.jsonl") keys = [z.split()[:2] for z in open(a.schluessel, encoding="utf-8") if z.strip()] offen = [(l, f) for l, f in keys if not os.path.exists(os.path.join(a.ziel, l, f + ".bin"))] From 5777b3ed4fd56c4a93703e87a150292a6c1ed3ed Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 10:55:19 +0100 Subject: [PATCH 3/6] Flop-Bibliothek nachschlagen: Stufen je Linie (Ordner @, weitere Kopfzeilen), die erste passende Lage gilt; Bedauern-Mass im Groessen-Vergleich Co-Authored-By: Claude Opus 5.5 --- entscheiden/motor/src/dienst.rs | 27 ++++++++++++++++++---- entscheiden/motor/src/flopbib.rs | 27 +++++++++++++++++++++- entscheiden/motor/src/flopbib_nach.rs | 33 +++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 5 deletions(-) diff --git a/entscheiden/motor/src/dienst.rs b/entscheiden/motor/src/dienst.rs index f5385d09..4726a19b 100644 --- a/entscheiden/motor/src/dienst.rs +++ b/entscheiden/motor/src/dienst.rs @@ -2000,11 +2000,30 @@ impl Motor { let iso_t = crate::flopbib::flop_text(iso); // Heads-up-Tisch (HU-Tafel): eigene Bilder unter hu/; gleiche Liniennamen bedeuten dort andere Ranges let hu = self.s.n == 2; - let bild = fb::bild(ordner, &art.pfad(hu), &linie, &iso_t); - let b = bild.as_ref().as_ref().map_err(|e| e.clone())?; let tol = art.toleranz_fuer(hu); - let zugelassen = fb::rake_zugelassen(crate::rake::regel(bb).and_then(|r| r.fuer_loeser(crate::rake::spieler(q))), b.rake, tol); - let skala = fb::gleiche_lage(b, a.pot, a.stack, a.rake, zugelassen, tol).map_err(|e| format!("{linie} {iso_t}: {e}"))?; + let regel = crate::rake::regel(bb).and_then(|r| r.fuer_loeser(crate::rake::spieler(q))); + // Stufen derselben Linie (weitere Kopfzeilen: Ordner @): die erste, deren Lage passt; sonst der Grund der Grundlinie + let unter = art.pfad(hu); + let mut gewaehlt: Option<(std::sync::Arc>, f64, String)> = None; + let mut grund: Option = None; + for l in fb::linien_mit_stufen(ordner, &unter, &linie) { + let bild = fb::bild(ordner, &unter, &l, &iso_t); + let pruef = match bild.as_ref() { + Ok(b) => fb::gleiche_lage(b, a.pot, a.stack, a.rake, fb::rake_zugelassen(regel, b.rake, tol), tol).map_err(|e| format!("{l} {iso_t}: {e}")), + Err(e) => Err(e.clone()), + }; + match pruef { + Ok(skala) => { + gewaehlt = Some((bild.clone(), skala, l)); + break; + } + Err(e) => { + grund.get_or_insert(e); + } + } + } + let Some((bild, skala, linie)) = gewaehlt else { return Err(grund.unwrap_or_else(|| format!("{unter}/{linie} {iso_t} fehlt"))) }; + let b = bild.as_ref().as_ref().map_err(|e| e.clone())?; let flop: Vec<(u8, i32)> = zuege.iter().filter(|e| e.strasse == 1).map(|e| (e.art, e.ziel.round() as i32)).collect(); let t = fb::nachschlagen(b, mich, &fb::hand_text(hand, perm), &flop, skala).map_err(|e| format!("{linie} {iso_t}: {e}"))?; let v: Vec<(Action, f32)> = t diff --git a/entscheiden/motor/src/flopbib.rs b/entscheiden/motor/src/flopbib.rs index 318f811c..36a9c2e8 100644 --- a/entscheiden/motor/src/flopbib.rs +++ b/entscheiden/motor/src/flopbib.rs @@ -342,6 +342,20 @@ pub fn verlust(s_bib: &[f32], s_echt: &[f32], q: &[f32], w: &[f32], n: usize) -> if masse > 0.0 { summe / masse } else { 0.0 } } +/// Bedauern der Mischung `s` gegen die beste Antwort am Knoten (Chips je Kombination, gewichtet mit `w`): max_a Q(a,h) - sum_a s(a,h) Q(a,h). +/// Nie negativ; der Unterschied zweier Mischungen am selben Knoten ist ihr Wertunterschied. +pub fn bedauern(s: &[f32], q: &[f32], w: &[f32], n: usize) -> f64 { + let z = q.len() / n; + let (mut summe, mut masse) = (0.0f64, 0.0f64); + for h in (0..n).filter(|&h| w[h] > 0.0) { + let best = (0..z).map(|a| q[a * n + h] as f64).fold(f64::MIN, f64::max); + let wert = (0..z).map(|a| s[a * n + h] as f64 * q[a * n + h] as f64).sum::(); + summe += w[h] as f64 * (best - wert); + masse += w[h] as f64; + } + if masse > 0.0 { summe / masse } else { 0.0 } +} + /// Spiel der Lage loesen (Live-Menue, Ziel FLOPBIB_ZIEL) und abschliessen. fn geloest(v: &Value, flop: [u8; 3], ziel: f32) -> Result<(Aufgabe, PostFlopGame), String> { let auf = aufgabe(v, flop)?; @@ -472,9 +486,11 @@ fn groesse_vergleich(a: &[String]) -> Result<(), String> { } } let verl = verlust(&s_bib, &s_echt, &q, &w2, n); + let (r_bib, r_echt) = (bedauern(&s_bib, &q, &w2, n), bedauern(&s_echt, &q, &w2, n)); let l = |g: &PostFlopGame, p: i32| postflop_solver::compute_exploitability(g) / p as f32 * 100.0; println!("{}", json!({"linie": linie, "flop": flop_s, "x": x, "wer_setzt": wer, "einsatz": einsatz, "bib_zug": format!("{:?}", bz[j]), - "verlust_topf_prozent": verl / auf.pot as f64 * 100.0, "luecke_prozent": [l(&gb, ab.pot), l(&ge, auf.pot)], + "verlust_topf_prozent": verl / auf.pot as f64 * 100.0, "bedauern_bib_prozent": r_bib / auf.pot as f64 * 100.0, + "bedauern_echt_prozent": r_echt / auf.pot as f64 * 100.0, "mehr_bedauern_prozent": (r_bib - r_echt) / auf.pot as f64 * 100.0, "luecke_prozent": [l(&gb, ab.pot), l(&ge, auf.pot)], "zuege_bib": gb.available_actions().iter().map(|x| format!("{x:?}")).collect::>(), "zuege_echt": ge.available_actions().iter().map(|x| format!("{x:?}")).collect::>()})); Ok(()) } @@ -835,6 +851,15 @@ mod spec { assert_eq!(zuege_abbilden(&[A::Check], &[A::Fold, A::Call], 1.0), None); } + #[test] + fn bedauern_gegen_die_beste_antwort_nie_negativ() { + // Hand 0: Q = (10, 4): reine 0 -> 0, halb/halb -> 3; Hand 1: Q = (0, 0) -> 0 + let q = [10.0, 0.0, 4.0, 0.0]; + assert!((bedauern(&[1.0, 0.5, 0.0, 0.5], &q, &[1.0, 1.0], 2) - 0.0).abs() < 1e-9); + assert!((bedauern(&[0.5, 0.5, 0.5, 0.5], &q, &[1.0, 1.0], 2) - 1.5).abs() < 1e-9); + assert!((bedauern(&[0.0, 1.0, 1.0, 0.0], &q, &[3.0, 1.0], 2) - 4.5).abs() < 1e-9); + } + #[test] fn verlust_ist_wert_der_echten_mischung_minus_wert_der_bibliotheksmischung() { // 2 Zuege, 2 Haende; Hand 0: Q = (10, 4), echt spielt Zug 0, Bibliothek halb/halb -> Verlust 3; Hand 1: gleich -> 0 diff --git a/entscheiden/motor/src/flopbib_nach.rs b/entscheiden/motor/src/flopbib_nach.rs index f26ab4d3..560ea7f4 100644 --- a/entscheiden/motor/src/flopbib_nach.rs +++ b/entscheiden/motor/src/flopbib_nach.rs @@ -422,6 +422,26 @@ pub fn bild(wurzel: &str, unter: &str, linie: &str, iso: &str) -> Arc@` neben ``), Grundlinie zuerst, Stufen +/// alphabetisch. Die Ordnerliste wird einmal je Unterordner gelesen. +pub fn linien_mit_stufen(wurzel: &str, unter: &str, linie: &str) -> Vec { + static LISTE: OnceLock>>>> = OnceLock::new(); + let dir = format!("{wurzel}/{unter}/bilder"); + let c = LISTE.get_or_init(|| Mutex::new(HashMap::new())); + let namen = { + let mut m = c.lock().unwrap_or_else(|e| e.into_inner()); + m.entry(dir.clone()) + .or_insert_with(|| { + let mut v: Vec = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect(); + v.sort(); + Arc::new(v) + }) + .clone() + }; + let praefix = format!("{linie}@"); + std::iter::once(linie.to_string()).chain(namen.iter().filter(|n| n.starts_with(&praefix)).cloned()).collect() +} + /// RSS des eigenen Prozesses in Bytes (ps), fuer die Lade-Messung. fn rss() -> u64 { std::process::Command::new("ps") @@ -535,6 +555,19 @@ mod spec { let _ = std::fs::remove_dir_all(&wurzel); } + #[test] + fn stufen_einer_linie_grundlinie_zuerst_und_nur_mit_at() { + let wurzel = std::env::temp_dir().join(format!("flopbib-stufen-{}", std::process::id())); + let w = wurzel.to_string_lossy().to_string(); + for d in ["BTN-BB", "BTN-BB@o4", "BTN-BB@e12", "BTN-BBX", "SB-BB@o4"] { + std::fs::create_dir_all(format!("{w}/srp/bilder/{d}")).unwrap(); + } + assert_eq!(linien_mit_stufen(&w, "srp", "BTN-BB"), vec!["BTN-BB", "BTN-BB@e12", "BTN-BB@o4"]); + assert_eq!(linien_mit_stufen(&w, "srp", "SB-BB"), vec!["SB-BB", "SB-BB@o4"]); + assert_eq!(linien_mit_stufen(&w, "3bet", "SBxBTN"), vec!["SBxBTN"]); + let _ = std::fs::remove_dir_all(&wurzel); + } + #[test] fn rake_zugelassen_nur_bei_gleichem_satz_und_deckel_im_band() { let eng = Toleranz { topf: (1.0, 1.0), spr: (1.0, 1.0), deckel: (1.0, 1.0) }; From 069e439153a8e0429ed8ffa4c4c852e8d77d53e3 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 12:12:48 +0100 Subject: [PATCH 4/6] Flop-Bibliothek: Einbindung in die Antwort testbar (mischung_fuer, bibliothek_antwort, exakt_text, ordner_von als reine Funktionen) und Specs dafuer (flopbib_dienst_spec.rs); Farm-Treiber prueft den Platz Co-Authored-By: Claude Opus 5.5 --- entscheiden/motor/src/dienst.rs | 107 ++++++----------- entscheiden/motor/src/flopbib_dienst_spec.rs | 118 +++++++++++++++++++ entscheiden/motor/src/flopbib_nach.rs | 89 +++++++++++++- entscheiden/motor/src/main.rs | 2 + messung/motor/flopbib/farm/flopbib_farm.py | 12 ++ 5 files changed, 254 insertions(+), 74 deletions(-) create mode 100644 entscheiden/motor/src/flopbib_dienst_spec.rs diff --git a/entscheiden/motor/src/dienst.rs b/entscheiden/motor/src/dienst.rs index 4726a19b..264fbf16 100644 --- a/entscheiden/motor/src/dienst.rs +++ b/entscheiden/motor/src/dienst.rs @@ -1494,28 +1494,13 @@ impl Motor { // MOTOR_FLOP_BIBLIOTHEK (flopbib_nach.rs): Mischung aus der Flop-Bibliothek statt der Loesung, wo sie dasselbe Spiel ist if let Some(ordner) = crate::flopbib_nach::ordner() { match self.flop_bibliothek(ordner, q, &a, zuege, oop, ip, mich, hand, brett, bb) { - Ok((v, werte, text)) => { - if q["suche_frueh"] == true { - return Ok(Some(json!({"action": "ABSTAIN", "size": null, "confidence": 0, "reason": format!("suche_frueh: {text}")}))); - } - let (i, akt, groesse) = ziehe(q, &v, salz, bb, stack == voll)?; - let zug_text = v.iter().map(|(a, p)| format!("{a:?} {:.0}%", p * 100.0)).collect::>().join(", "); - let grund = format!("motor FLOP {text} ({} ms, Topf {} Rest {}): {zug_text}", t0.elapsed().as_millis(), a.pot, a.stack); - let werte_j: Vec = v.iter().enumerate().map(|(j, (x, p))| { - let (ar, zi) = match x { Action::Fold => (0, 0), Action::Check | Action::Call => (1, 0), Action::Bet(b) | Action::Raise(b) | Action::AllIn(b) => (2, *b), _ => (9, 0) }; - json!([ar, zi as f64 / 100.0, p, werte.as_ref().map(|w| w[j]), Value::Null]) - }).collect(); - return Ok(Some(json!({"action": akt, "size": groesse, "confidence": v[i].1, "reason": grund, "werte": werte_j}))); - } + Ok(m) => return bibliothek_antwort(q, &m, salz, bb, stack == voll, t0.elapsed().as_millis(), a.pot, a.stack).map(Some), Err(e) => BIB_NOTIZ.with(|n| *n.borrow_mut() = Some(format!("Bibliothek: {e}"))), } } let (k, g, ausbeutung, text) = self.flop_geloest(&a, &zuege_von(1), q["suche_frueh"] == true)?; // MOTOR_FLOP_BIBLIOTHEK: Rueckfall auf Flop exakt - der Grund steht im Zuggrund (in der Klammer, die nl2.rs nicht liest) - let text = match BIB_NOTIZ.with(|n| n.borrow_mut().take()) { - Some(g) => format!("{text}; {g}"), - None => text, - }; + let text = crate::flopbib_nach::exakt_text(text, BIB_NOTIZ.with(|n| n.borrow_mut().take())); if q["suche_frueh"] == true { let e = crate::flop_exakt::einstellung().as_ref().ok().cloned().flatten().ok_or("Einstellung")?; crate::flop_exakt::merke(k, g, ausbeutung, e.merker_bytes); @@ -1989,64 +1974,17 @@ impl Motor { Ok((k, g, w)) } - /// MOTOR_FLOP_BIBLIOTHEK: Mischung der Hand aus der Flop-Bibliothek -> (Mischung mit Zuegen des echten Topfs, Werte je Zug in bb (flopbib-2), - /// Text fuer den Zuggrund); sonst der Grund, warum nicht. + /// MOTOR_FLOP_BIBLIOTHEK: Topfart und Linie aus dem Vorflop-Weg, dann die Mischung der Hand (`flopbib_nach::mischung_fuer`); sonst der Grund. #[allow(clippy::too_many_arguments)] - fn flop_bibliothek(&self, ordner: &str, q: &Value, a: &Aufgabe, zuege: &[Echt], oop: usize, ip: usize, mich: usize, hand: (u8, u8), brett: &[u8], bb: f64) -> Result<(Vec<(Action, f32)>, Option>, String), String> { + fn flop_bibliothek(&self, ordner: &str, q: &Value, a: &Aufgabe, zuege: &[Echt], oop: usize, ip: usize, mich: usize, hand: (u8, u8), brett: &[u8], bb: f64) -> Result { use crate::flopbib_nach as fb; let vorflop: Vec<(usize, u8)> = zuege.iter().filter(|e| e.strasse == 0).map(|e| (e.sitz as usize, e.art)).collect(); let (art, linie) = fb::lage_art(oop, ip, &vorflop)?; - let (iso, perm) = fb::iso_mit([brett[0], brett[1], brett[2]]); - let iso_t = crate::flopbib::flop_text(iso); - // Heads-up-Tisch (HU-Tafel): eigene Bilder unter hu/; gleiche Liniennamen bedeuten dort andere Ranges - let hu = self.s.n == 2; - let tol = art.toleranz_fuer(hu); - let regel = crate::rake::regel(bb).and_then(|r| r.fuer_loeser(crate::rake::spieler(q))); - // Stufen derselben Linie (weitere Kopfzeilen: Ordner @): die erste, deren Lage passt; sonst der Grund der Grundlinie - let unter = art.pfad(hu); - let mut gewaehlt: Option<(std::sync::Arc>, f64, String)> = None; - let mut grund: Option = None; - for l in fb::linien_mit_stufen(ordner, &unter, &linie) { - let bild = fb::bild(ordner, &unter, &l, &iso_t); - let pruef = match bild.as_ref() { - Ok(b) => fb::gleiche_lage(b, a.pot, a.stack, a.rake, fb::rake_zugelassen(regel, b.rake, tol), tol).map_err(|e| format!("{l} {iso_t}: {e}")), - Err(e) => Err(e.clone()), - }; - match pruef { - Ok(skala) => { - gewaehlt = Some((bild.clone(), skala, l)); - break; - } - Err(e) => { - grund.get_or_insert(e); - } - } - } - let Some((bild, skala, linie)) = gewaehlt else { return Err(grund.unwrap_or_else(|| format!("{unter}/{linie} {iso_t} fehlt"))) }; - let b = bild.as_ref().as_ref().map_err(|e| e.clone())?; let flop: Vec<(u8, i32)> = zuege.iter().filter(|e| e.strasse == 1).map(|e| (e.art, e.ziel.round() as i32)).collect(); - let t = fb::nachschlagen(b, mich, &fb::hand_text(hand, perm), &flop, skala).map_err(|e| format!("{linie} {iso_t}: {e}"))?; - let v: Vec<(Action, f32)> = t - .mischung - .iter() - .map(|(z, p)| { - let x = match *z { - fb::Zug::Fold => Action::Fold, - fb::Zug::Check => Action::Check, - fb::Zug::Call => Action::Call, - fb::Zug::Bet(x) => Action::Bet(x.min(a.stack)), - fb::Zug::Raise(x) => Action::Raise(x.min(a.stack)), - fb::Zug::AllIn(_) => Action::AllIn(a.stack), - }; - (x, *p) - }) - .collect(); - let summe: f32 = v.iter().map(|x| x.1).sum(); - if summe <= 0.0 { - return Err("Mischung leer".into()); - } - let v = v.into_iter().map(|(x, p)| (x, p / summe)).collect(); - Ok((v, t.werte, format!("Bibliothek {} {linie} {iso_t} Luecke {:.2} %", art.pfad(hu), b.luecke_topf * 100.0))) + let regel = crate::rake::regel(bb).and_then(|r| r.fuer_loeser(crate::rake::spieler(q))); + // Heads-up-Tisch (HU-Tafel): eigene Bilder unter hu/; gleiche Liniennamen bedeuten dort andere Ranges + let lage = fb::Lage { pot: a.pot, stack: a.stack, rake: a.rake, regel, hu: self.s.n == 2 }; + fb::mischung_fuer(ordner, art, &linie, [brett[0], brett[1], brett[2]], hand, mich, &flop, &lage) } /// MOTOR_FLOP_EXAKT: Flop-Spiel aus dem Merker oder geloest, wenn die erwartete Zeit in die Frist passt (flop_exakt.rs). @@ -2110,7 +2048,7 @@ impl Motor { /// Schluessel einer Aufgabe fuer den Merker: Topf, Stapel, Brett, Ranges. /// Zieht aus der Mischung `v` (Summe 1) mit dem Seed der Anfrage einen Zug und macht ihn zur Tisch-Aktion: (Index, Aktion, Groesse in Geld). /// `voller_stapel`: der Baum hat den ganzen Stapel (All-in = maxRaiseTo). -fn ziehe(q: &Value, v: &[(Action, f32)], salz: u64, bb: f64, voller_stapel: bool) -> Result<(usize, &'static str, Option), String> { +pub(crate) fn ziehe(q: &Value, v: &[(Action, f32)], salz: u64, bb: f64, voller_stapel: bool) -> Result<(usize, &'static str, Option), String> { let seed = q["seed"].as_u64().unwrap_or(1); let w: Vec = v.iter().map(|x| x.1).collect(); let i = waehle(&mut Rng(misch(seed, salz) | 1), &w); @@ -2136,6 +2074,33 @@ fn ziehe(q: &Value, v: &[(Action, f32)], salz: u64, bb: f64, voller_stapel: bool Ok((i, akt, groesse)) } +/// MOTOR_FLOP_BIBLIOTHEK: Antwort aus der Mischung der Bibliothek (Zug mit dem Seed der Anfrage gezogen wie bei Flop exakt); bei +/// `suche_frueh` nur die Notiz, dass nichts vorzurechnen ist. +#[allow(clippy::too_many_arguments)] +pub(crate) fn bibliothek_antwort(q: &Value, m: &crate::flopbib_nach::Mischung, salz: u64, bb: f64, voller_stapel: bool, ms: u128, pot: i32, rest: i32) -> Result { + if q["suche_frueh"] == true { + return Ok(json!({"action": "ABSTAIN", "size": null, "confidence": 0, "reason": format!("suche_frueh: {}", m.text)})); + } + let v = &m.v; + let (i, akt, groesse) = ziehe(q, v, salz, bb, voller_stapel)?; + let zug_text = v.iter().map(|(a, p)| format!("{a:?} {:.0}%", p * 100.0)).collect::>().join(", "); + let grund = format!("motor FLOP {} ({ms} ms, Topf {pot} Rest {rest}): {zug_text}", m.text); + let werte_j: Vec = v + .iter() + .enumerate() + .map(|(j, (x, p))| { + let (ar, zi) = match x { + Action::Fold => (0, 0), + Action::Check | Action::Call => (1, 0), + Action::Bet(b) | Action::Raise(b) | Action::AllIn(b) => (2, *b), + _ => (9, 0), + }; + json!([ar, zi as f64 / 100.0, p, m.werte.as_ref().map(|w| w[j]), Value::Null]) + }) + .collect(); + Ok(json!({"action": akt, "size": groesse, "confidence": v[i].1, "reason": grund, "werte": werte_j})) +} + fn schluessel(a: &Aufgabe) -> u64 { let mut k = misch(a.pot as u64, a.stack as u64); for c in &a.brett { diff --git a/entscheiden/motor/src/flopbib_dienst_spec.rs b/entscheiden/motor/src/flopbib_dienst_spec.rs new file mode 100644 index 00000000..de0d34c0 --- /dev/null +++ b/entscheiden/motor/src/flopbib_dienst_spec.rs @@ -0,0 +1,118 @@ +//! Spezifikation der Einbindung von MOTOR_FLOP_BIBLIOTHEK in die Antwort des Dienstes (dienst.rs `flop_bibliothek`, `bibliothek_antwort`, +//! `ziehe`; flopbib_nach.rs `mischung_fuer`, `exakt_text`, `ordner_von`): Treffer mit Zug, Zuggrund und Betrag; Rueckfall mit Grund, wenn +//! das Bild fehlt, die Lage oder die Rake nicht passt; am Heads-up-Tisch kein 6-max-Bild gleichen Namens; ohne Schalter kein Ordner. +use crate::dienst::{bibliothek_antwort, ziehe}; +use crate::flopbib_nach::{exakt_text, mischung_fuer, ordner_von, spec::bild_roh, Lage, Topfart}; +use postflop_solver::Action; +use serde_json::json; + +fn k(s: &str) -> u8 { + let r = b"23456789TJQKA".iter().position(|&c| c == s.as_bytes()[0]).unwrap() as u8; + let f = b"cdhs".iter().position(|&c| c == s.as_bytes()[1]).unwrap() as u8; + r * 4 + f +} + +/// Wurzel mit dem kleinen Bild (BTN-BB, Flop Ks7h2d) unter srp/bilder/BTN-BB/.bin. +fn wurzel(name: &str) -> (String, [u8; 3]) { + let w = std::env::temp_dir().join(format!("flopbib-dienst-{name}-{}", std::process::id())).to_string_lossy().to_string(); + let flop = [k("Ks"), k("7h"), k("2d")]; + let iso = crate::flopbib::flop_text(crate::flopbib::kanonisch(flop)); + std::fs::create_dir_all(format!("{w}/srp/bilder/BTN-BB")).unwrap(); + std::fs::write(format!("{w}/srp/bilder/BTN-BB/{iso}.bin"), bild_roh(false)).unwrap(); + (w, flop) +} + +/// Eine echte Hand, die nach der Farbvertauschung des Flops die Bibliothekshand `ziel` ist. +fn hand_fuer(flop: [u8; 3], ziel: &str) -> (u8, u8) { + let (_, perm) = crate::flopbib_nach::iso_mit(flop); + (0..52u8).flat_map(|a| (a + 1..52).map(move |b| (a, b))).find(|&h| crate::flopbib_nach::hand_text(h, perm) == ziel).unwrap() +} + +fn lage() -> Lage { + Lage { pot: 550, stack: 6600, rake: (0.05, 1000.0), regel: Some((0.05, 1000.0)), hu: false } +} + +fn anfrage(seed: u64) -> serde_json::Value { + json!({"bigBlind": 0.02, "seed": seed, "toCall": 0.0, "minRaiseTo": 0.02, "maxRaiseTo": 1.32, "legalActions": ["FOLD", "CHECK", "RAISE"]}) +} + +#[test] +fn treffer_zug_kommt_aus_der_bibliothek_mit_zuggrund_und_betrag() { + let (w, flop) = wurzel("treffer"); + let m = mischung_fuer(&w, Topfart::Srp, "BTN-BB", flop, hand_fuer(flop, "AdAh"), 0, &[], &lage()).unwrap(); + assert_eq!(m.v.iter().map(|x| x.0).collect::>(), vec![Action::Check, Action::Bet(275)]); + assert!((m.v[0].1 - 0.25).abs() < 1e-4 && (m.v[1].1 - 0.75).abs() < 1e-4); + assert!(m.text.starts_with("Bibliothek srp BTN-BB "), "{}", m.text); + // beide Zuege kommen bei verschiedenen Seeds vor; Betrag des Einsatzes = 275/100 bb + let mut gesehen = (false, false); + for seed in 1..40 { + let q = anfrage(seed); + let a = bibliothek_antwort(&q, &m, 7, 0.02, true, 3, 550, 6600).unwrap(); + let (i, akt, groesse) = ziehe(&q, &m.v, 7, 0.02, true).unwrap(); + assert_eq!(a["action"], akt); + assert_eq!(a["size"].as_f64(), groesse); + assert_eq!(a["confidence"].as_f64().map(|x| x as f32), Some(m.v[i].1)); + let r = a["reason"].as_str().unwrap(); + assert!(r.starts_with("motor FLOP Bibliothek srp BTN-BB ") && r.ends_with("Check 25%, Bet(275) 75%"), "{r}"); + assert!(r.contains("(3 ms, Topf 550 Rest 6600)"), "{r}"); + assert_eq!(a["werte"].as_array().unwrap().len(), 2); + match akt { + "CHECK" => gesehen.0 = true, + "RAISE" => { + gesehen.1 = true; + assert!((groesse.unwrap() - 0.055).abs() < 1e-9, "{groesse:?}"); + } + x => panic!("{x}"), + } + } + assert!(gesehen.0 && gesehen.1); + // suche_frueh: nichts vorzurechnen + let mut q = anfrage(1); + q["suche_frueh"] = json!(true); + let a = bibliothek_antwort(&q, &m, 7, 0.02, true, 3, 550, 6600).unwrap(); + assert_eq!(a["action"], "ABSTAIN"); + assert!(a["reason"].as_str().unwrap().starts_with("suche_frueh: Bibliothek srp BTN-BB")); + let _ = std::fs::remove_dir_all(&w); +} + +#[test] +fn rueckfall_mit_grund_wenn_bild_lage_oder_rake_nicht_passt() { + let (w, flop) = wurzel("rueckfall"); + let h = hand_fuer(flop, "AdAh"); + // Bild fehlt + let e = mischung_fuer(&w, Topfart::Srp, "CO-BB", flop, h, 0, &[], &lage()).unwrap_err(); + assert!(e.starts_with("srp/CO-BB ") && e.ends_with("fehlt"), "{e}"); + // Lage passt nicht (Topf weit ueber der Toleranz) + let e = mischung_fuer(&w, Topfart::Srp, "BTN-BB", flop, h, 0, &[], &Lage { pot: 2000, stack: 24000, ..lage() }).unwrap_err(); + assert!(e.contains("Topf 2000 statt 550"), "{e}"); + // Rake: anderer Satz; Limit ohne Regel + let e = mischung_fuer(&w, Topfart::Srp, "BTN-BB", flop, h, 0, &[], &Lage { regel: Some((0.04, 1000.0)), ..lage() }).unwrap_err(); + assert!(e.contains("Rake"), "{e}"); + let e = mischung_fuer(&w, Topfart::Srp, "BTN-BB", flop, h, 0, &[], &Lage { regel: None, ..lage() }).unwrap_err(); + assert!(e.contains("Rake"), "{e}"); + // Einsatz ausserhalb des Baums + let e = mischung_fuer(&w, Topfart::Srp, "BTN-BB", flop, hand_fuer(flop, "4c5c"), 1, &[(2, 450)], &lage()).unwrap_err(); + assert!(e.contains("Groesse 450"), "{e}"); + // der Grund landet im Zuggrund von Flop exakt; ohne Grund bleibt der Text + assert_eq!(exakt_text("1200 ms geloest".into(), Some(format!("Bibliothek: {e}"))), format!("1200 ms geloest; Bibliothek: {e}")); + assert_eq!(exakt_text("gemerkt".into(), None), "gemerkt"); + let _ = std::fs::remove_dir_all(&w); +} + +#[test] +fn heads_up_tisch_nimmt_kein_6max_bild_gleichen_namens() { + let (w, flop) = wurzel("hu"); + let h = hand_fuer(flop, "AdAh"); + let hu = Lage { hu: true, rake: (0.05, 250.0), regel: Some((0.05, 250.0)), ..lage() }; + let e = mischung_fuer(&w, Topfart::Srp, "BTN-BB", flop, h, 0, &[], &hu).unwrap_err(); + assert!(e.starts_with("hu/srp/BTN-BB ") && e.ends_with("fehlt"), "{e}"); + let _ = std::fs::remove_dir_all(&w); +} + +#[test] +fn ohne_schalter_kein_ordner() { + assert_eq!(ordner_von(|_| None), None); + assert_eq!(ordner_von(|_| Some(" ".into())), None); + assert_eq!(ordner_von(|k| (k == "MOTOR_FLOP_BIBLIOTHEK").then(|| " D:\\bib ".into())), Some("D:\\bib".into())); + assert_eq!(ordner_von(|k| (k == "ANDERES").then(|| "x".into())), None); +} diff --git a/entscheiden/motor/src/flopbib_nach.rs b/entscheiden/motor/src/flopbib_nach.rs index 560ea7f4..ea9c648b 100644 --- a/entscheiden/motor/src/flopbib_nach.rs +++ b/entscheiden/motor/src/flopbib_nach.rs @@ -51,7 +51,90 @@ const VORFLOP_REIHE: [usize; 6] = [2, 3, 4, 5, 0, 1]; pub fn ordner() -> Option<&'static str> { static O: OnceLock> = OnceLock::new(); - O.get_or_init(|| std::env::var("MOTOR_FLOP_BIBLIOTHEK").ok().filter(|x| !x.trim().is_empty())).as_deref() + O.get_or_init(|| ordner_von(|k| std::env::var(k).ok())).as_deref() +} + +/// Liest ausschliesslich MOTOR_FLOP_BIBLIOTHEK; leer oder nicht gesetzt = aus. +pub fn ordner_von(umgebung: impl Fn(&str) -> Option) -> Option { + umgebung("MOTOR_FLOP_BIBLIOTHEK").map(|x| x.trim().to_string()).filter(|x| !x.is_empty()) +} + +/// Zuggrund von Flop exakt mit dem Grund, warum die Bibliothek nicht griff (in der Klammer, die nl2.rs nicht liest). +pub fn exakt_text(text: String, notiz: Option) -> String { + match notiz { + Some(g) => format!("{text}; {g}"), + None => text, + } +} + +/// Die echte Lage, wie der Dienst sie rechnet (Topf, Stapel in 1/100 bb; Rake wie `Aufgabe::rake`; `regel` = Satz/Deckel der Rake-Regel +/// des Limits fuer den Loeser; `hu` = Heads-up-Tisch mit HU-Tafel). +#[derive(Clone, Copy, Debug)] +pub struct Lage { + pub pot: i32, + pub stack: i32, + pub rake: (f64, f64), + pub regel: Option<(f64, f64)>, + pub hu: bool, +} + +/// Mischung der Bibliothek fuer die Hand, Zuege auf den echten Topf skaliert, Summe 1; Werte je Zug (flopbib-2); Text fuer den Zuggrund. +#[derive(Clone, Debug)] +pub struct Mischung { + pub v: Vec<(postflop_solver::Action, f32)>, + pub werte: Option>, + pub text: String, +} + +/// Bild der Linie (oder einer ihrer Stufen, deren Lage passt), Knoten ueber die echten Flop-Zuege, Mischung der Hand; sonst der Grund. +#[allow(clippy::too_many_arguments)] +pub fn mischung_fuer(wurzel: &str, art: Topfart, linie: &str, flop: [u8; 3], hand: (u8, u8), mich: usize, flop_zuege: &[(u8, i32)], lage: &Lage) -> Result { + use postflop_solver::Action; + let (iso, perm) = iso_mit(flop); + let iso_t = flopbib::flop_text(iso); + let tol = art.toleranz_fuer(lage.hu); + let unter = art.pfad(lage.hu); + let mut gewaehlt: Option<(Arc>, f64, String)> = None; + let mut grund: Option = None; + for l in linien_mit_stufen(wurzel, &unter, linie) { + let bild = bild(wurzel, &unter, &l, &iso_t); + let pruef = match bild.as_ref() { + Ok(b) => gleiche_lage(b, lage.pot, lage.stack, lage.rake, rake_zugelassen(lage.regel, b.rake, tol), tol).map_err(|e| format!("{l} {iso_t}: {e}")), + Err(e) => Err(e.clone()), + }; + match pruef { + Ok(skala) => { + gewaehlt = Some((bild.clone(), skala, l)); + break; + } + Err(e) => { + grund.get_or_insert(e); + } + } + } + let Some((bild, skala, linie)) = gewaehlt else { return Err(grund.unwrap_or_else(|| format!("{unter}/{linie} {iso_t} fehlt"))) }; + let b = bild.as_ref().as_ref().map_err(|e| e.clone())?; + let t = nachschlagen(b, mich, &hand_text(hand, perm), flop_zuege, skala).map_err(|e| format!("{linie} {iso_t}: {e}"))?; + let v: Vec<(Action, f32)> = t + .mischung + .iter() + .map(|(z, p)| { + let x = match *z { + Zug::Fold => Action::Fold, + Zug::Check => Action::Check, + Zug::Call => Action::Call, + Zug::Bet(x) => Action::Bet(x.min(lage.stack)), + Zug::Raise(x) => Action::Raise(x.min(lage.stack)), + Zug::AllIn(_) => Action::AllIn(lage.stack), + }; + (x, *p) + }) + .collect(); + let summe: f32 = v.iter().map(|x| x.1).sum(); + if summe <= 0.0 { + return Err("Mischung leer".into()); + } + Ok(Mischung { v: v.into_iter().map(|(x, p)| (x, p / summe)).collect(), werte: t.werte, text: format!("Bibliothek {unter} {linie} {iso_t} Luecke {:.2} %", b.luecke_topf * 100.0) }) } /// Zug der Bibliothek (Betraege in 1/100 bb wie im Loeser: Gesamteinsatz dieser Strasse). @@ -490,7 +573,7 @@ pub fn lade_messung(wurzel: &str) -> Result { } #[cfg(test)] -mod spec { +pub(crate) mod spec { use super::*; use serde_json::json; @@ -634,7 +717,7 @@ mod spec { } /// Kleines Bild von Hand: Wurzel OOP (Check, Bet(275)), IP nach Check (Check, Bet(275)), IP nach Bet (Fold, Call, Raise(1100)). - fn bild_roh(format2: bool) -> Vec { + pub(crate) fn bild_roh(format2: bool) -> Vec { let knoten = json!([ {"weg": [], "spieler": 0, "zuege": ["Check", "Bet(275)"]}, {"weg": [0], "spieler": 1, "zuege": ["Check", "Bet(275)"]}, diff --git a/entscheiden/motor/src/main.rs b/entscheiden/motor/src/main.rs index 10cfdf95..e2f8d306 100644 --- a/entscheiden/motor/src/main.rs +++ b/entscheiden/motor/src/main.rs @@ -17,6 +17,8 @@ mod flopwert; mod flop_exakt; mod flopbib; mod flopbib_nach; +#[cfg(test)] +mod flopbib_dienst_spec; mod groessen; mod glueck; mod karten; diff --git a/messung/motor/flopbib/farm/flopbib_farm.py b/messung/motor/flopbib/farm/flopbib_farm.py index 015a42f8..93d9dec1 100644 --- a/messung/motor/flopbib/farm/flopbib_farm.py +++ b/messung/motor/flopbib/farm/flopbib_farm.py @@ -13,6 +13,7 @@ ap.add_argument("--parallel", type=int, default=3) ap.add_argument("--faeden", type=int, default=8) ap.add_argument("--menue", default=None) ap.add_argument("--zielluecke", default="1.0") +ap.add_argument("--min-frei-gb", type=float, default=5.0, help="vor jedem Schluessel: so viel muss auf dem Ziel-Laufwerk frei sein, sonst Ende") ap.add_argument("--warte-stunden", type=float, default=6.0, help="so lange auf die Exe warten (Bau als eigener Auftrag)") a = ap.parse_args() bis = time.time() + a.warte_stunden * 3600 @@ -24,10 +25,21 @@ log = os.path.join(os.path.dirname(os.path.abspath(a.ziel)), f"fertig-{a.name}.j keys = [z.split()[:2] for z in open(a.schluessel, encoding="utf-8") if z.strip()] offen = [(l, f) for l, f in keys if not os.path.exists(os.path.join(a.ziel, l, f + ".bin"))] print(f"{time.strftime('%H:%M:%S')} {len(keys)} Schluessel, {len(offen)} offen", flush=True) +if platz_gb() < a.min_frei_gb: + raise SystemExit(f"zu wenig Platz auf dem Ziel-Laufwerk: {platz_gb():.1f} GB frei, mindestens {a.min_frei_gb} GB") + + +import shutil + + +def platz_gb(): + return shutil.disk_usage(os.path.splitdrive(os.path.abspath(a.ziel))[0] + os.sep).free / 1e9 def eins(k): linie, flop = k + if platz_gb() < a.min_frei_gb: + return {"linie": linie, "flop": flop, "fehler": f"zu wenig Platz ({platz_gb():.1f} GB frei, mindestens {a.min_frei_gb} GB)"} os.makedirs(os.path.join(a.ziel, linie), exist_ok=True) aus = os.path.join(a.ziel, linie, flop + ".bin") env = dict(os.environ, RAYON_NUM_THREADS=str(a.faeden), FLOPBIB_ZIEL=a.zielluecke) From b355b9f8c913b3ac98ec9e9a7455c55a2ff09f5a Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 12:52:58 +0100 Subject: [PATCH 5/6] Farm-Treiber: platz_gb vor der ersten Nutzung (NameError behoben, wie auf dem Spielrechner), --schon; kopie_vergleich.py Co-Authored-By: Claude Opus 5.5 --- messung/motor/flopbib/farm/flopbib_farm.py | 18 ++++----- messung/motor/flopbib/farm/kopie_vergleich.py | 39 +++++++++++++++++++ 2 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 messung/motor/flopbib/farm/kopie_vergleich.py diff --git a/messung/motor/flopbib/farm/flopbib_farm.py b/messung/motor/flopbib/farm/flopbib_farm.py index 93d9dec1..abc051f9 100644 --- a/messung/motor/flopbib/farm/flopbib_farm.py +++ b/messung/motor/flopbib/farm/flopbib_farm.py @@ -4,7 +4,7 @@ Bibliotheksordner (//.bin), wie der Motor sie liest (MOTOR_FLO python -X utf8 flopbib_farm.py --exe E --lagen L --schluessel S --ziel D:\\...\\flopbib-v2\\srp\\bilder --name N [--parallel 3] [--faeden 8] [--menue eng|breit] [--zielluecke 1.0] Die Schlange setzt die Prioritaet (BelowNormal) und haelt den Lauf an, solange der Laeufer spielt.""" -import argparse, json, os, subprocess, time, concurrent.futures as cf +import argparse, json, os, shutil, subprocess, time, concurrent.futures as cf ap = argparse.ArgumentParser() for k in ("exe", "lagen", "schluessel", "ziel", "name"): @@ -13,9 +13,16 @@ ap.add_argument("--parallel", type=int, default=3) ap.add_argument("--faeden", type=int, default=8) ap.add_argument("--menue", default=None) ap.add_argument("--zielluecke", default="1.0") +ap.add_argument("--schon", action="append", default=[], help="weitere Bilder-Ordner: dort fertige Schluessel werden uebersprungen (z. B. alte Ablage, die kopiert wird)") ap.add_argument("--min-frei-gb", type=float, default=5.0, help="vor jedem Schluessel: so viel muss auf dem Ziel-Laufwerk frei sein, sonst Ende") ap.add_argument("--warte-stunden", type=float, default=6.0, help="so lange auf die Exe warten (Bau als eigener Auftrag)") a = ap.parse_args() + + +def platz_gb(): + return shutil.disk_usage(os.path.splitdrive(os.path.abspath(a.ziel))[0] + os.sep).free / 1e9 + + bis = time.time() + a.warte_stunden * 3600 while not os.path.exists(a.exe): if time.time() > bis: @@ -23,19 +30,12 @@ while not os.path.exists(a.exe): time.sleep(30) log = os.path.join(os.path.dirname(os.path.abspath(a.ziel)), f"fertig-{a.name}.jsonl") keys = [z.split()[:2] for z in open(a.schluessel, encoding="utf-8") if z.strip()] -offen = [(l, f) for l, f in keys if not os.path.exists(os.path.join(a.ziel, l, f + ".bin"))] +offen = [(l, f) for l, f in keys if not any(os.path.exists(os.path.join(d, l, f + ".bin")) for d in [a.ziel] + a.schon)] print(f"{time.strftime('%H:%M:%S')} {len(keys)} Schluessel, {len(offen)} offen", flush=True) if platz_gb() < a.min_frei_gb: raise SystemExit(f"zu wenig Platz auf dem Ziel-Laufwerk: {platz_gb():.1f} GB frei, mindestens {a.min_frei_gb} GB") -import shutil - - -def platz_gb(): - return shutil.disk_usage(os.path.splitdrive(os.path.abspath(a.ziel))[0] + os.sep).free / 1e9 - - def eins(k): linie, flop = k if platz_gb() < a.min_frei_gb: diff --git a/messung/motor/flopbib/farm/kopie_vergleich.py b/messung/motor/flopbib/farm/kopie_vergleich.py new file mode 100644 index 00000000..22a1d07a --- /dev/null +++ b/messung/motor/flopbib/farm/kopie_vergleich.py @@ -0,0 +1,39 @@ +"""Kopiert die Bibliothek von einer Wurzel in eine andere (nur neue Dateien, nie ueberschreiben, Quelle nur lesen) und vergleicht danach je +Topfart-Ordner Anzahl und Bytesumme: Quelle gesamt, Ziel fuer dieselben Dateien, Ziel gesamt. + python -X utf8 kopie_vergleich.py """ +import os, shutil, sys, time +quelle, ziel, bericht = sys.argv[1], sys.argv[2], sys.argv[3] +neu = 0 +for wurzel, _, dateien in os.walk(quelle): + rel = os.path.relpath(wurzel, quelle) + for d in dateien: + if d.endswith(".tmp"): + continue + z = os.path.join(ziel, rel, d) + if os.path.exists(z): + continue + os.makedirs(os.path.dirname(z), exist_ok=True) + shutil.copyfile(os.path.join(wurzel, d), z + ".tmp") + os.replace(z + ".tmp", z) + neu += 1 +def summe(w, nur=None): + n = b = 0 + for r, _, ds in os.walk(w): + for d in ds: + if d.endswith(".tmp"): + continue + rel = os.path.relpath(os.path.join(r, d), w) + if nur is not None and rel not in nur: + continue + n += 1; b += os.path.getsize(os.path.join(r, d)) + return n, b +zeilen = [f"{time.strftime('%d.%m. %H:%M')} Kopie {quelle} -> {ziel}: {neu} Dateien neu kopiert"] +for art in sorted(set(os.listdir(quelle)) | set(os.listdir(ziel) if os.path.isdir(ziel) else [])): + q = os.path.join(quelle, art); z = os.path.join(ziel, art) + qset = set(os.path.relpath(os.path.join(r, d), q) for r, _, ds in os.walk(q) for d in ds if not d.endswith(".tmp")) if os.path.isdir(q) else set() + nq, bq = summe(q) if os.path.isdir(q) else (0, 0) + nzq, bzq = summe(z, qset) if os.path.isdir(z) else (0, 0) + nz, bz = summe(z) if os.path.isdir(z) else (0, 0) + zeilen.append(f"{art:10s} Quelle {nq} Dateien {bq} Bytes | Ziel davon {nzq} Dateien {bzq} Bytes | Ziel gesamt {nz} Dateien {bz} Bytes | {'GLEICH' if (nq, bq) == (nzq, bzq) else 'ABWEICHUNG'}") +open(bericht, "a", encoding="utf-8").write("\n".join(zeilen) + "\n") +print("\n".join(zeilen)) From 1711ef28c079be45880b86b68594009ff9222a3b Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 5 Dec 2026 14:42:49 +0100 Subject: [PATCH 6/6] Flop-Bibliothek nachschlagen: Einsatz-Band 0,66-1,5 der Bibliotheksgroesse (gemessen: echte Einsaetze 0,33-0,75 Topf hoechstens 0,76 % Topf Mehr-Bedauern; 1,0 Topf 1,27 %); Erhoehungen weiter +-15 % Co-Authored-By: Claude Opus 5.5 --- entscheiden/motor/src/flopbib_nach.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/entscheiden/motor/src/flopbib_nach.rs b/entscheiden/motor/src/flopbib_nach.rs index ea9c648b..6d7cf417 100644 --- a/entscheiden/motor/src/flopbib_nach.rs +++ b/entscheiden/motor/src/flopbib_nach.rs @@ -44,6 +44,11 @@ pub const TOLERANZ_LIMPRAISE: Toleranz = Toleranz { topf: (0.99, 1.01), spr: (0. pub const HU_DECKEL: (f64, f64) = (1.0, 1.04); /// Einsatz des Gegners darf hoechstens so weit (relativ) vom naechsten Bibliothekszug abweichen. pub const GROESSE_TOLERANZ: f64 = 0.15; +/// Ein echter Einsatz (nicht Erhoehung) wird auf den naechsten Einsatz der Bibliothek abgebildet, wenn er das 0,66- bis 1,5-Fache davon ist. +/// Gemessen (05.12., `flopbib --groesse-vergleich`, BTN-BB und SBxBTN, je 2 Flops, Gegner setzt 0,33/0,40/0,66/0,75/1,0 Topf an der Wurzel +/// und nach Check; Mass: Mehr-Bedauern unserer Antwort gegen die echte Loesung, nur Knoten mit konvergierter echter Loesung): 0,33 bis 0,75 +/// Topf hoechstens 0,76 % Topf (meist unter 0,25 %); 1,0 Topf einmal 1,27 % - darum endet das Band bei 0,75/0,5 = 1,5. +pub const EINSATZ_BAND: (f64, f64) = (0.66, 1.5); /// Baumsitze des Dienstes (6-max) -> Positionsnamen der Linien. pub const NAMEN: [&str; 6] = ["SB", "BB", "UTG", "HJ", "CO", "BTN"]; /// Reihenfolge vorflop (wer zuerst handelt). @@ -454,7 +459,12 @@ pub fn nachschlagen(b: &Bild, spieler: usize, hand: &str, zuege: &[(u8, i32)], s .filter_map(|(i, z)| z.betrag().map(|x| (i, x as f64 * skala))) .min_by(|a, b| (a.1 - ziel as f64).abs().total_cmp(&(b.1 - ziel as f64).abs())) .ok_or("kein Einsatz im Knoten")?; - if (ziel as f64 / x - 1.0).abs() > GROESSE_TOLERANZ { + let r = ziel as f64 / x; + let passt = match k.zuege[i] { + Zug::Bet(_) => r >= EINSATZ_BAND.0 - 1e-9 && r <= EINSATZ_BAND.1 + 1e-9, + _ => (r - 1.0).abs() <= GROESSE_TOLERANZ, + }; + if !passt { return Err(format!("Groesse {ziel} nicht in der Bibliothek (naechste {x:.0})")); } Some(i) @@ -785,8 +795,12 @@ pub(crate) mod spec { // skaliert: echter Topf 600 (skala 600/550), Einsatz 300 = 50 % -> Bibliothekszug 275*skala = 300; Raise skaliert auf 1200 let t = nachschlagen(&b, 1, "4c5c", &[(2, 300)], 600.0 / 550.0).unwrap(); assert_eq!(t.mischung[2].0, Zug::Raise(1200)); - // Einsatz 400 (45 % daneben): nicht in der Bibliothek - assert!(nachschlagen(&b, 1, "4c5c", &[(2, 400)], 1.0).unwrap_err().contains("Groesse")); + // Einsatz 400 (das 1,45-Fache von 275): im gemessenen Band, also derselbe Knoten; 182 (0,66-fach) ebenso + assert!(nachschlagen(&b, 1, "4c5c", &[(2, 400)], 1.0).is_ok()); + assert!(nachschlagen(&b, 1, "4c5c", &[(2, 182)], 1.0).is_ok()); + // 1,0 Topf (550, das 2-Fache) und 0,25 Topf (138, das 0,5-Fache): nicht in der Bibliothek + assert!(nachschlagen(&b, 1, "4c5c", &[(2, 550)], 1.0).unwrap_err().contains("Groesse")); + assert!(nachschlagen(&b, 1, "4c5c", &[(2, 138)], 1.0).unwrap_err().contains("Groesse")); // Hand fehlt assert!(nachschlagen(&b, 1, "AsAc", &[(1, 0)], 1.0).unwrap_err().contains("Hand")); // falscher Spieler am Knoten (OOP nach Check ist nicht am Zug)