diff --git a/entscheiden/decide.py b/entscheiden/decide.py index 754bbae7..40a3224c 100644 --- a/entscheiden/decide.py +++ b/entscheiden/decide.py @@ -38,7 +38,7 @@ SCHALTER_DATEI = os.path.join(BASE, "..", "betrieb", "kern_schalter.txt") # GEGNER_ZAEHLUNG=1 ist kein Kern-Schalter, sondern einer des Laeufers (betrieb/runner.py): die gezaehlten # Reads je Gegner gehen in die Profile. Er steht hier, damit er in der Arm-Marke jeder Hand steht. BEKANNTE_SCHALTER = ("MDF_UNREAD", "RAISE_DRAWS", "RAISE_PRIOR", "TURN_SPIEL", "GRUNDSTRATEGIE", "OPEN_JAM", - "SOLVER_RIVER", "SOLVER_KERN", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3", "SOLVER3_OHNE", "SOLVER3_MS", "SOLVER3_ROHNE", "SOLVER3_FOHNE", "SOLVER3_TOHNE", "SOLVER3_FSPERRE", "SOLVER3_ALLE", "SOLVER3_FORM", "ALLIN_EINSATZ", "ALLIN_RANGE", + "SOLVER_RIVER", "SOLVER_KERN", "SOLVER_TURN", "SOLVER_FLOP", "SOLVER_RIVER3", "SOLVER_TURN3", "SOLVER_FLOP3", "SOLVER3_OHNE", "SOLVER3_MS", "SOLVER3_ROHNE", "SOLVER3_FOHNE", "SOLVER3_TOHNE", "SOLVER3_FSPERRE", "SOLVER3_ALLE", "SOLVER3_FORM", "SOLVER3_POOL", "SOLVER3_LINIE", "ALLIN_EINSATZ", "ALLIN_RANGE", "RAKE_LIVE", "GEGNER_ZAEHLUNG", "GEGNER_SHOWDOWN", "GEGNER_RANGE", "GEGNER_BREIT", "GEGNER_POOL", "GEGNER_POOL_STUFE", "RERAISE_TIEFE", "RERAISE_BLUFF", "TURN_RAISE_BLUFF", "TURN_RAISE_NUR", "STATION_POSTFLOP", "POKERINTEL", diff --git a/src/bin/kern_zeile.rs b/src/bin/kern_zeile.rs new file mode 100644 index 00000000..5f76ddee --- /dev/null +++ b/src/bin/kern_zeile.rs @@ -0,0 +1,56 @@ +//! Diagnosis: the multiway solver's row for one request. `kern_zeile [zeilennummer ab 0]`. +//! Prints the street's solver (river / turn / flop), the acts, hero's average row, iterations and combos. + +use rechner::json::{parse, Value}; + +fn feld<'a>(v: &'a Value, k: &str) -> Option<&'a Value> { + match v { + Value::Object(m) => m.iter().find(|(n, _)| n == k).map(|(_, x)| x), + _ => None, + } +} + +fn main() { + rechner::engine::start::aus_umgebung(); + let pfad = std::env::args().nth(1).expect("kern_zeile [n]"); + let nur: Option = std::env::args().nth(2).and_then(|x| x.parse().ok()); + for (i, zeile) in std::fs::read_to_string(pfad).expect("datei").lines().filter(|l| !l.trim().is_empty()).enumerate() { + if nur.is_some_and(|n| n != i) { + continue; + } + let Ok(v) = parse(zeile) else { continue }; + let req = feld(&v, "anfrage").or_else(|| feld(&v, "req")).unwrap_or(&v); + let Ok(spot) = rechner::wire::decode::decode(req).map_err(|_| ()).and_then(|s| rechner::guard::validate::check(s).map_err(|_| ())) else { + println!("{i}\tdecode"); + continue; + }; + print!("{i} spot {:?} {:?} {:?} pot {:.2} toCall {:.2} klasse {} ", spot.street, spot.hero_cards, spot.board, spot.pot, spot.to_call, rechner::sim::poolruf::KLASSEN[rechner::sim::poolruf::klasse(&spot.hero_cards, &spot.board)]); + if std::env::var("KERN_RANGE").is_ok() { + if let Some((_, vl)) = rechner::engine::river_spieler::model_lists(&spot) { + let mut zaehl = std::collections::BTreeMap::new(); + for (c, _) in &vl { + *zaehl.entry(rechner::sim::poolruf::KLASSEN[rechner::sim::poolruf::klasse(c, &spot.board)]).or_insert(0usize) += 1; + } + let mut paare = std::collections::BTreeMap::new(); + for (c, _) in &vl { + let k = format!("{:?}{:?}", c[0].rank, c[1].rank); + *paare.entry(k).or_insert(0usize) += 1; + } + println!("[range] {} combos, klassen {:?} +[range] {:?}", vl.len(), zaehl, paare); + } + } + let gated = rechner::engine::read_gate::gate_reads(&spot); + if spot.street == rechner::game::Street::River { print!("[bereiche] {i} (sitz, n, besser, gleich, schlechter) {:?}", rechner::engine::river3_spieler::debug_bereiche(&gated)); } + match spot.street { + rechner::game::Street::River => match rechner::engine::river3_spieler::solve_river3(&gated) { + Some(s) => println!("{i}\triver3 {:?} {:?} iters {} combos {:?}", s.acts, s.row.iter().map(|x| (x * 100.0).round() / 100.0).collect::>(), s.iterations, s.combos), + None => println!("{i}\tkein river3 {:?}", rechner::engine::multi3_spieler::grund_nehmen()), + }, + _ => match rechner::engine::multi3_spieler::solve_multi3(&gated) { + Some(s) => println!("{i}\tmulti3 {:?} {:?} iters {} combos {:?}", s.acts, s.row.iter().map(|x| (x * 100.0).round() / 100.0).collect::>(), s.iterations, s.combos), + None => println!("{i}\tkein multi3 {:?}", rechner::engine::multi3_spieler::grund_nehmen()), + }, + } + } +} diff --git a/src/cfr/multi3.rs b/src/cfr/multi3.rs index 0579e2ee..e8710bc1 100644 --- a/src/cfr/multi3.rs +++ b/src/cfr/multi3.rs @@ -44,6 +44,9 @@ pub struct GameM { /// Players who never decide: they check, and call every bet up to the cap (the pooled field of a /// 5+-handed spot, their hands still sampled and in the showdown). Bit mask, 0 = none. pub passive: u32, + /// The observed line of street 0 and hero's index (`build_linie`). + line: Vec<(usize, Act)>, + me: usize, } #[derive(Clone)] @@ -56,6 +59,8 @@ struct State { street: usize, /// Every player's contribution at the start of this street. level: f64, + /// Position in the observed line while the walk is on it (`build_linie`, street 0 only). + lp: Option, } impl GameM { @@ -66,9 +71,15 @@ impl GameM { /// As `build`, the players in the bit mask `passive` only check or call. pub fn build_passiv(players: usize, pot: f64, cap: f64, menus: &[Menu3], slots: usize, passive: u32) -> GameM { - let mut g = GameM { nodes: Vec::new(), players, pot, cap, slots: slots.max(1), passive }; + Self::build_linie(players, pot, cap, menus, slots, passive, &[], 0) + } + + /// As `build_passiv`, with the observed street-0 `line` at its exact sizes (see `river3::Game3::build_linie`). + #[allow(clippy::too_many_arguments)] + pub fn build_linie(players: usize, pot: f64, cap: f64, menus: &[Menu3], slots: usize, passive: u32, line: &[(usize, Act)], me: usize) -> GameM { + let mut g = GameM { nodes: Vec::new(), players, pot, cap, slots: slots.max(1), passive, line: line.to_vec(), me }; let all = (1u32 << players) - 1; - let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0, street: 0, level: 0.0 }; + let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0, street: 0, level: 0.0, lp: if line.is_empty() { None } else { Some(0) } }; g.grow(s, menus); g } @@ -96,7 +107,7 @@ impl GameM { let id = self.nodes.len(); self.nodes.push(NodeM::Deal { kids: Vec::new() }); let first = (0..self.players).find(|p| s.active & (1 << p) != 0).unwrap_or(0); - let t = State { pending: s.active, raises: 0, to_act: first, street: s.street + 1, level: top, ..s.clone() }; + let t = State { pending: s.active, raises: 0, to_act: first, street: s.street + 1, level: top, lp: None, ..s.clone() }; // Every slot has the same betting tree; they are separate nodes (the regrets differ per card). let kids: Vec = (0..self.slots).map(|_| self.grow(t.clone(), menus)).collect(); if let NodeM::Deal { kids: k } = &mut self.nodes[id] { @@ -149,11 +160,48 @@ impl GameM { } } } + // The observed line (street 0): which act it takes here, and the exact size of an observed bet or raise. + let mut on: Option<(usize, bool)> = None; + if let Some(i) = s.lp { + if let Some((who, obs)) = self.line.get(i).cloned() { + if who == p { + match obs { + Act::Bet(x) | Act::Raise(x) => { + let kind = |t: &Act| matches!((&obs, t), (Act::Bet(_), Act::Bet(_)) | (Act::Raise(_), Act::Raise(_))); + let facing = top > s.c[p] + eps; + let erlaubt = x > top + eps && x < self.cap - eps && !acts.iter().any(|t| kind(t) && matches!(t, Act::Bet(y) | Act::Raise(y) if (y - x).abs() < eps)); + let platz = if facing { s.raises < menu.max_raises && matches!(obs, Act::Raise(_)) } else { matches!(obs, Act::Bet(_)) }; + if erlaubt && platz && self.passive & (1 << p) == 0 { + let at = acts.iter().position(|t| matches!(t, Act::Bet(y) | Act::Raise(y) if kind(t) && *y > x)).unwrap_or(acts.len()); + acts.insert(at, if matches!(obs, Act::Bet(_)) { Act::Bet(x) } else { Act::Raise(x) }); + totals.insert(at, x); + } + on = acts + .iter() + .enumerate() + .filter_map(|(k, t)| match t { + Act::Bet(y) | Act::Raise(y) if kind(t) => Some((k, (y - x).abs())), + _ => None, + }) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(k, _)| (k, true)); + } + _ => on = acts.iter().position(|t| *t == obs).map(|k| (k, true)), + } + } else if p != self.me { + on = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call))).map(|k| (k, false)); + } + } + } let id = self.nodes.len(); self.nodes.push(NodeM::Dec { player: p, street: s.street, acts: acts.clone(), kids: Vec::new() }); let mut kids = Vec::with_capacity(acts.len()); - for (a, total) in acts.iter().zip(&totals) { + for (j, (a, total)) in acts.iter().zip(&totals).enumerate() { let mut t = s.clone(); + t.lp = match (s.lp, on) { + (Some(i), Some((k, eigene))) if k == j => Some(if eigene { i + 1 } else { i }), + _ => None, + }; t.pending &= !(1 << p); match a { Act::Fold => t.active &= !(1 << p), @@ -235,6 +283,53 @@ impl GameM { Some(at) } + /// The nodes the observed line passes (node, index of the act taken), as `follow_nachsicht` walks it: a player whose + /// turn comes before his recorded act and who is not `me` folds (bet open) or checks. Ends at `me`'s next node. + pub fn pfad_nachsicht(&self, line: &[(usize, Act)], me: usize) -> Option> { + let mut at = 0; + let mut pfad = Vec::new(); + let skip = |at: usize, pfad: &mut Vec<(usize, usize)>| -> Option { + let NodeM::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; + let k = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call)))?; + pfad.push((at, k)); + Some(kids[k]) + }; + for (who, a) in line { + loop { + let NodeM::Dec { player, .. } = &self.nodes[at] else { return None }; + if player == who { + break; + } + if *player == me { + return None; + } + at = skip(at, &mut pfad)?; + } + let NodeM::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; + let k = match a { + Act::Bet(x) | Act::Raise(x) => acts + .iter() + .enumerate() + .filter_map(|(k, t)| match t { + Act::Bet(y) | Act::Raise(y) => Some((k, (y - x).abs())), + _ => None, + }) + .min_by(|p, q| p.1.total_cmp(&q.1))? + .0, + _ => acts.iter().position(|t| t == a)?, + }; + pfad.push((at, k)); + at = kids[k]; + } + while let NodeM::Dec { player, .. } = &self.nodes[at] { + if *player == me { + break; + } + at = skip(at, &mut pfad)?; + } + Some(pfad) + } + /// The child of `at` that the observed act `a` leads to (nearest size for bets and raises). fn step(&self, at: usize, a: &Act) -> Option { let NodeM::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; @@ -289,6 +384,8 @@ pub struct SolverM { avg: Vec>, rng: Xs, t: u64, + /// As `river3::Solver3`: the pool's row per hand and its weight per node. + locks: Vec, f64)>>, } /// One iteration's sampled cards. @@ -329,7 +426,13 @@ impl SolverM { NodeM::Dec { player, street: 0, acts, .. } => vec![0.0; hands[*player].masks.len() * acts.len()], _ => Vec::new(), }).collect(); - SolverM { game, hands, board, slot_cards, extra, cum, regret, avg, rng: Xs(seed | 1), t: 0 } + let locks = vec![None; game.nodes.len()]; + SolverM { game, hands, board, slot_cards, extra, cum, regret, avg, rng: Xs(seed | 1), t: 0, locks } + } + + /// Lock `node`'s player to the pool rows `rows` (one row per hand over the node's acts) with weight `w`. + pub fn lock(&mut self, node: usize, rows: Vec, w: f64) { + self.locks[node] = Some((rows, w.clamp(0.0, 1.0))); } pub fn masks(&self, p: usize) -> &[u64] { @@ -496,6 +599,11 @@ impl SolverM { let h = d.picked[p]; let mut sigma = vec![0.0; a]; Self::current(&self.regret[node][h * a..(h + 1) * a], a, &mut sigma); + if let Some((rows, w)) = &self.locks[node] { + for (k, s) in sigma.iter_mut().enumerate() { + *s = (1.0 - w) * *s + w * rows[h * a + k]; + } + } let x = self.rng.unit(); let mut acc = 0.0; let mut k = a - 1; @@ -529,6 +637,14 @@ impl SolverM { } } + /// Diagnosis: the hand's regrets at `node` per action in chips (weighted mean of `value(a) - value(strategy)`). + pub fn regret_chips(&self, node: usize, h: usize) -> Vec { + let NodeM::Dec { acts, .. } = &self.game.nodes[node] else { return Vec::new() }; + let a = acts.len(); + let z = (self.t * (self.t + 1)) as f64 / 2.0; + self.regret[node][h * a..(h + 1) * a].iter().map(|r| r / z).collect() + } + pub fn iterations(&self) -> u64 { self.t } diff --git a/src/cfr/river3.rs b/src/cfr/river3.rs index ea29a31e..cf2befb5 100644 --- a/src/cfr/river3.rs +++ b/src/cfr/river3.rs @@ -54,6 +54,9 @@ pub struct Game3 { /// Players who never decide: they check, and call every bet up to the cap (the pooled field of a /// 5+-handed spot, their hands still sampled and in the showdown). Bit mask, 0 = none. pub passive: u32, + /// The observed line the tree is built for (`build_linie`): its bets and raises are in the tree at their exact size. + line: Vec<(usize, Act)>, + me: usize, } #[derive(Clone)] @@ -63,6 +66,8 @@ struct State { pending: u32, raises: u8, to_act: usize, + /// Position in the observed line while the walk is on it (`build_linie`). + lp: Option, } impl Game3 { @@ -74,9 +79,17 @@ impl Game3 { /// As `build`, the players in the bit mask `passive` only check or call. pub fn build_passiv(players: usize, pot: f64, cap: f64, menu: &Menu3, passive: u32) -> Game3 { - let mut g = Game3 { nodes: Vec::new(), players, pot, cap, passive }; + Self::build_linie(players, pot, cap, menu, passive, &[], 0) + } + + /// As `build_passiv`, with the observed `line` in the tree at its exact sizes: an observed bet or raise of a size the menu + /// does not hold is an extra act at its node (the nearest menu size would change the price hero faces: a min-bet of 2 % + /// of the pot became a third of the pot). `me` = hero's index; a player before him whose act is not in the line is + /// skipped as `follow_nachsicht` does. Empty `line`: the plain tree. + pub fn build_linie(players: usize, pot: f64, cap: f64, menu: &Menu3, passive: u32, line: &[(usize, Act)], me: usize) -> Game3 { + let mut g = Game3 { nodes: Vec::new(), players, pot, cap, passive, line: line.to_vec(), me }; let all = (1u32 << players) - 1; - let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0 }; + let s = State { c: vec![0.0; players], active: all, pending: all, raises: 0, to_act: 0, lp: if line.is_empty() { None } else { Some(0) } }; g.grow(s, menu); g } @@ -121,11 +134,48 @@ impl Game3 { acts.extend(sizes.into_iter().map(Act::Bet)); } } + // The observed line: which act it takes here (`on`), and the exact size of an observed bet or raise. + let mut on: Option<(usize, bool)> = None; + if let Some(i) = s.lp { + if let Some((who, obs)) = self.line.get(i).cloned() { + if who == p { + match obs { + Act::Bet(x) | Act::Raise(x) => { + let kind = |t: &Act| matches!((&obs, t), (Act::Bet(_), Act::Bet(_)) | (Act::Raise(_), Act::Raise(_))); + let facing = top > s.c[p] + eps; + let erlaubt = x > top + eps && x < self.cap - eps && !acts.iter().any(|t| kind(t) && matches!(t, Act::Bet(y) | Act::Raise(y) if (y - x).abs() < eps)); + let platz = if facing { s.raises < menu.max_raises && matches!(obs, Act::Raise(_)) } else { matches!(obs, Act::Bet(_)) }; + if erlaubt && platz && self.passive & (1 << p) == 0 { + let at = acts.iter().position(|t| matches!(t, Act::Bet(y) | Act::Raise(y) if kind(t) && *y > x)).unwrap_or(acts.len()); + // An all-in raise stays last; the new size goes in front of it. + acts.insert(at, if matches!(obs, Act::Bet(_)) { Act::Bet(x) } else { Act::Raise(x) }); + } + on = acts + .iter() + .enumerate() + .filter_map(|(k, t)| match t { + Act::Bet(y) | Act::Raise(y) if kind(t) => Some((k, (y - x).abs())), + _ => None, + }) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(k, _)| (k, true)); + } + _ => on = acts.iter().position(|t| *t == obs).map(|k| (k, true)), + } + } else if p != self.me { + on = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call))).map(|k| (k, false)); + } + } + } let id = self.nodes.len(); self.nodes.push(Node3::Dec { player: p, acts: acts.clone(), kids: Vec::new() }); let mut kids = Vec::with_capacity(acts.len()); - for a in &acts { + for (j, a) in acts.iter().enumerate() { let mut t = s.clone(); + t.lp = match (s.lp, on) { + (Some(i), Some((k, eigene))) if k == j => Some(if eigene { i + 1 } else { i }), + _ => None, + }; t.pending &= !(1 << p); match a { Act::Fold => t.active &= !(1 << p), @@ -211,6 +261,53 @@ impl Game3 { Some(at) } + /// The nodes the observed line passes (node, index of the act taken), as `follow_nachsicht` walks it: a player whose + /// turn comes before his recorded act and who is not `me` folds (bet open) or checks. Ends at `me`'s next node. + pub fn pfad_nachsicht(&self, line: &[(usize, Act)], me: usize) -> Option> { + let mut at = 0; + let mut pfad = Vec::new(); + let skip = |at: usize, pfad: &mut Vec<(usize, usize)>| -> Option { + let Node3::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; + let k = acts.iter().position(|t| *t == Act::Fold).or_else(|| acts.iter().position(|t| matches!(t, Act::Check | Act::Call)))?; + pfad.push((at, k)); + Some(kids[k]) + }; + for (who, a) in line { + loop { + let Node3::Dec { player, .. } = &self.nodes[at] else { return None }; + if player == who { + break; + } + if *player == me { + return None; + } + at = skip(at, &mut pfad)?; + } + let Node3::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; + let k = match a { + Act::Bet(x) | Act::Raise(x) => acts + .iter() + .enumerate() + .filter_map(|(k, t)| match t { + Act::Bet(y) | Act::Raise(y) => Some((k, (y - x).abs())), + _ => None, + }) + .min_by(|p, q| p.1.total_cmp(&q.1))? + .0, + _ => acts.iter().position(|t| t == a)?, + }; + pfad.push((at, k)); + at = kids[k]; + } + while let Node3::Dec { player, .. } = &self.nodes[at] { + if *player == me { + break; + } + at = skip(at, &mut pfad)?; + } + Some(pfad) + } + /// The child of `at` that the observed act `a` leads to (nearest size for bets and raises). fn step(&self, at: usize, a: &Act) -> Option { let Node3::Dec { acts, kids, .. } = &self.nodes[at] else { return None }; @@ -260,6 +357,9 @@ pub struct Solver3 { avg: Vec>, rng: Xs, t: u64, + /// Per node: the measured pool's row per hand (hand-major) and its weight; the player plays `(1 - w) * CFR + w * row` + /// where the others see him (node-locking as in the heads-up core, `TrSolver::lock`). + locks: Vec, f64)>>, } impl Solver3 { @@ -282,7 +382,13 @@ impl Solver3 { }; let regret = sized(&|p, a| hands[p].masks.len() * a); let avg = sized(&|p, a| hands[p].masks.len() * a); - Solver3 { game, hands, score, cum, regret, avg, rng: Xs(seed | 1), t: 0 } + let locks = vec![None; game.nodes.len()]; + Solver3 { game, hands, score, cum, regret, avg, rng: Xs(seed | 1), t: 0, locks } + } + + /// Lock `node`'s player to the pool rows `rows` (one row per hand over the node's acts) with weight `w`. + pub fn lock(&mut self, node: usize, rows: Vec, w: f64) { + self.locks[node] = Some((rows, w.clamp(0.0, 1.0))); } pub fn masks(&self, p: usize) -> &[u64] { @@ -423,6 +529,11 @@ impl Solver3 { let h = picked[p]; let mut sigma = vec![0.0; a]; Self::current(&self.regret[node][h * a..(h + 1) * a], a, &mut sigma); + if let Some((rows, w)) = &self.locks[node] { + for (k, s) in sigma.iter_mut().enumerate() { + *s = (1.0 - w) * *s + w * rows[h * a + k]; + } + } let x = self.rng.unit(); let mut acc = 0.0; let mut k = a - 1; @@ -452,6 +563,14 @@ impl Solver3 { } } + /// Diagnosis: the hand's regrets at `node` per action, scaled to chips (weighted mean of `value(a) - value(strategy)`). + pub fn regret_chips(&self, node: usize, h: usize) -> Vec { + let Node3::Dec { acts, .. } = &self.game.nodes[node] else { return Vec::new() }; + let a = acts.len(); + let z = (self.t * (self.t + 1)) as f64 / 2.0; + self.regret[node][h * a..(h + 1) * a].iter().map(|r| r / z).collect() + } + pub fn iterations(&self) -> u64 { self.t } diff --git a/src/cfr/river3/tests.rs b/src/cfr/river3/tests.rs index a96e7ef1..5c3b7f30 100644 --- a/src/cfr/river3/tests.rs +++ b/src/cfr/river3/tests.rs @@ -109,3 +109,77 @@ fn timing() { s.run(10_000); eprintln!("{nodes} nodes, 200 hands each, 10000 iterations: {:.0} ms", t.elapsed().as_secs_f64() * 1e3); } + +/// Lock every villain node that faces a bet to the pool's answer: the weakest `fold` share of the range folds, the rest +/// calls (`rank` = a hand's share of the range it beats). +fn lock_pool(s: &mut Solver3, me: usize, h: &Hands3, board: u64, fold: f64) { + let score: Vec = h.masks.iter().map(|m| fast7::score(m | board)).collect(); + let rank: Vec = score.iter().map(|x| score.iter().filter(|y| *y < x).count() as f64 / score.len() as f64).collect(); + let jobs: Vec<(usize, usize)> = s + .game + .nodes + .iter() + .enumerate() + .filter_map(|(i, n)| match n { + Node3::Dec { player, acts, .. } if *player != me && acts.contains(&Act::Fold) => Some((i, acts.len())), + _ => None, + }) + .collect(); + for (i, a) in jobs { + let mut rows = Vec::new(); + for r in &rank { + let mut row = vec![0.0; a]; + row[if *r < fold { 0 } else { 1 }] = 1.0; + rows.extend(row); + } + s.lock(i, rows, 1.0); + } +} + +/// The cause of the multiway river's "thin value never bets" (20.11.): equilibrium villains fold every hand that loses to +/// a bet and never pay off with a worse one, so a bet earns nothing over a check. Against villains that answer like the +/// measured pool (the weakest 40 % fold, the rest calls) top pair bets. +#[test] +fn thin_value_bets_against_pool_callers_and_not_against_equilibrium_villains() { + let b = board(); + let h = all_hands(b); + let hero = idx(&h, "As 9s"); + let bets = |s: &Solver3, at: usize| { + let Node3::Dec { acts, .. } = s.game.nodes[at].clone() else { panic!() }; + prob(&s.row(at, hero), &acts, |a| matches!(a, Act::Bet(_))) + }; + let g = Game3::build(3, 10.0, 100.0, &Menu3::standard()); + let mut cfr = Solver3::new(g.clone(), vec![h.clone(), h.clone(), h.clone()], b, 3); + cfr.run(8_000); + let mut pool = Solver3::new(g, vec![h.clone(), h.clone(), h.clone()], b, 3); + lock_pool(&mut pool, 0, &h, b, 0.4); + pool.run(8_000); + let (c, p) = (bets(&cfr, 0), bets(&pool, 0)); + assert!(p > 0.8, "pool callers: bets {p:.2}"); + assert!(p > c, "bets {p:.2} against the pool, {c:.2} against equilibrium villains"); +} + +/// A played act is fixed: with the villain's bet locked to probability 1, hero's node is reached in every iteration and +/// its row is the response to the bet (air folds, the nuts do not). +#[test] +fn a_locked_line_makes_hero_learn_at_every_iteration() { + let b = board(); + let h = all_hands(b); + let g = Game3::build(3, 10.0, 100.0, &Menu3::standard()); + let at = g.follow(&[(0, Act::Bet(7.5))]).unwrap(); + let pfad = g.pfad_nachsicht(&[(0, Act::Bet(7.5))], 1).unwrap(); + assert_eq!(pfad.len(), 1); + let mut s = Solver3::new(g, vec![h.clone(), h.clone(), h.clone()], b, 11); + let Node3::Dec { acts: a0, .. } = s.game.nodes[pfad[0].0].clone() else { panic!() }; + let mut rows = vec![0.0; h.masks.len() * a0.len()]; + for k in 0..h.masks.len() { + rows[k * a0.len() + pfad[0].1] = 1.0; + } + s.lock(pfad[0].0, rows, 1.0); + s.run(3_000); + let Node3::Dec { acts, .. } = s.game.nodes[at].clone() else { panic!() }; + let air = s.row(at, idx(&h, "6s 5d")); + assert!(prob(&air, &acts, |a| *a == Act::Fold) > 0.9, "{air:?} {acts:?}"); + let nuts = s.row(at, idx(&h, "As Ad")); + assert!(prob(&nuts, &acts, |a| *a == Act::Fold) < 0.05, "{nuts:?} {acts:?}"); +} diff --git a/src/engine/multi3_spieler.rs b/src/engine/multi3_spieler.rs index cf18f6ba..a8498c3f 100644 --- a/src/engine/multi3_spieler.rs +++ b/src/engine/multi3_spieler.rs @@ -51,6 +51,132 @@ static ALLE: AtomicBool = AtomicBool::new(false); /// the top-pair flop fold becomes a call. The answer stays the solver's (reason `solver-kern ... | form`). Default off. static FORM: AtomicBool = AtomicBool::new(false); +/// `SOLVER3_POOL=` (0 < w <= 1): the villains of the multiway solvers answer a bet like the measured pool instead of +/// like equilibrium players (weight `w`, the heads-up core's node lock). Cause of the hand rules `SOLVER3_FORM` and +/// `SOLVER3_FSPERRE` (20.11.): a CFR villain folds every hand that loses to hero's bet range and never pays off with a +/// worse hand, so thin value (trips, an overpair) is worth nothing against it and checking wins; the heads-up core had +/// the pool's fold curve all along (`wett_kurve`), the multiway solvers did not. Stored in thousandths, default 0 = off. +static POOL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +pub fn set_pool(w: f64) { + POOL.store((w.clamp(0.0, 1.0) * 1000.0).round() as u32, Ordering::Relaxed); +} + +pub(crate) fn pool_w() -> f64 { + POOL.load(Ordering::Relaxed) as f64 / 1000.0 +} + +/// `SOLVER3_LINIE=1`: the villains' acts already played on the observed line are fixed (the played act with probability 1). +/// Their ranges are the range model's of that line (the act is in them), but the tree let the act happen a second time by +/// the CFR strategy: a bet was weighted by how often CFR bets the hand (the range squared) and hero's node was reached in a +/// fraction of the iterations, with a row learned from a few noisy samples (the same double count the heads-up core fixed +/// with `linie=modell`). Default off. +static LINIE: AtomicBool = AtomicBool::new(false); + +pub fn set_linie(on: bool) { + LINIE.store(on, Ordering::Relaxed); +} + +pub(crate) fn linie() -> bool { + LINIE.load(Ordering::Relaxed) +} + +/// The locks of the played line: at each node of `pfad` of a player other than `me`, every hand plays the act taken. +/// `acts(node)` = the node's act count, `hands[p]` = player `p`'s combos. +pub(crate) fn linie_sperren(pfad: &[(usize, usize)], me: usize, spieler: &dyn Fn(usize) -> Option<(usize, usize)>, hands: &[usize]) -> Vec<(usize, Vec)> { + pfad.iter() + .filter_map(|&(node, k)| { + let (p, a) = spieler(node)?; + if p == me || a < 2 { + return None; + } + let mut rows = vec![0.0; hands[p] * a]; + for h in 0..hands[p] { + rows[h * a + k] = 1.0; + } + Some((node, rows)) + }) + .collect() +} + +/// The pool's answer of villain `p` (index in the acting order) at a node facing a bet: fold the weakest `fold` share of +/// his range (soft edge), raise the strongest `raise_pool` share, call the rest. `q` = each hand's rank in his range. +/// `ratio` = the last bet or raise over the pot before it, `allin_ab` = the ratio at which a bet is all-in. +fn pool_zeile(spot: &Spot, who: &Villain, acts: &[Act], q: &[f64], ratio: f64, allin_ab: f64) -> Option> { + let f = crate::exploit::wett_kurve::pool_fold(spot, spot.street, ratio, allin_ab, who.profile.as_ref())?; + let allin = ratio >= allin_ab - 1e-9; + let r = if allin { 0.0 } else { crate::engine::solver_kern::raise_pool(ratio) }; + let fold_i = acts.iter().position(|a| *a == Act::Fold)?; + let call_i = acts.iter().position(|a| *a == Act::Call)?; + let raise_i = acts.iter().enumerate().filter_map(|(i, a)| if let Act::Raise(x) = a { Some((i, *x)) } else { None }).min_by(|a, b| a.1.total_cmp(&b.1)).map(|x| x.0); + let mut rows = Vec::with_capacity(q.len() * acts.len()); + for &qi in q { + let mut row = vec![0.0; acts.len()]; + let pf = crate::engine::solver_kern::rampe(qi, f, 0.08, true); + let pr = if raise_i.is_some() { crate::engine::solver_kern::rampe(qi, r, 0.04, false) * (1.0 - pf) } else { 0.0 }; + row[fold_i] = pf; + if let Some(i) = raise_i { + row[i] = pr; + } + row[call_i] = (1.0 - pf - pr).max(0.0); + rows.extend(row); + } + Some(rows) +} + +/// What `pool_sperren` needs of a node: the actor, its acts and its kids (a deal node has none: the walk stops there). +pub(crate) enum KnotenSicht<'a> { + Dec { player: usize, acts: &'a [Act], kids: &'a [usize] }, + Ende, +} + +/// The nodes (index, pool rows) of the first betting round at which a villain faces a bet. `knoten(i)` shows node `i`; +/// `hands[p]` = player `p`'s combos (masks), `pot` the pot before the street, `cap` the common cap, `passive` the pooled +/// players (never decide). The walk follows the tree from the root keeping the street's contributions. +#[allow(clippy::too_many_arguments)] +pub(crate) fn pool_sperren<'a>( + spot: &Spot, + order: &[u8], + me: usize, + passive: u32, + masks: &[&[u64]], + board: u64, + pot: f64, + cap: f64, + knoten: &dyn Fn(usize) -> KnotenSicht<'a>, +) -> Vec<(usize, Vec)> { + let ranks: Vec> = masks.iter().map(|m| crate::engine::river_spieler::percentiles(m, &vec![1.0; m.len()], board)).collect(); + let mut out = Vec::new(); + // (node, contributions, last aggression: (increment, pot before it, level before it)) + let mut stack = vec![(0usize, vec![0.0; order.len()], (0.0f64, pot, 0.0f64, false))]; + while let Some((at, c, (incr, before, prev_top, geraist))) = stack.pop() { + let KnotenSicht::Dec { player, acts, kids } = knoten(at) else { continue }; + let top = c.iter().copied().fold(0.0, f64::max); + if player != me && passive & (1 << player) == 0 && acts.contains(&Act::Fold) && incr > 0.0 && !geraist { + if let Some(who) = spot.live_villains().find(|v| v.seat == order[player]) { + let allin_ab = (cap - prev_top) / before.max(1e-9); + if let Some(rows) = pool_zeile(spot, who, acts, &ranks[player], incr / before.max(1e-9), allin_ab) { + out.push((at, rows)); + } + } + } + for (a, k) in acts.iter().zip(kids) { + let mut t = c.clone(); + let mut agg = (incr, before, prev_top, geraist); + match a { + Act::Fold | Act::Check => {} + Act::Call => t[player] = top, + Act::Bet(x) | Act::Raise(x) => { + agg = (*x - top, pot + c.iter().sum::(), top, matches!(a, Act::Raise(_))); + t[player] = *x; + } + } + stack.push((*k, t, agg)); + } + } + out +} + /// The first street's menu; under `SOLVER3_ALLE` it allows as many raises as the observed line holds (the tree must /// contain the line), else as given. pub(crate) fn menu_fuer(line: &[(usize, Act)], mut menu: Menu3) -> Menu3 { @@ -192,6 +318,8 @@ pub fn ohne_from_env() { set_fsperre(std::env::var("SOLVER3_FSPERRE").as_deref() == Ok("1")); set_alle(std::env::var("SOLVER3_ALLE").as_deref() == Ok("1")); set_form(std::env::var("SOLVER3_FORM").as_deref() == Ok("1")); + set_linie(std::env::var("SOLVER3_LINIE").as_deref() == Ok("1")); + set_pool(std::env::var("SOLVER3_POOL").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0.0)); } /// `(nur_offen, ohne)` from `SOLVER_FLOP3` / `SOLVER_TURN3` / `SOLVER_RIVER3` = `offen` and @@ -356,7 +484,8 @@ pub fn solve_multi3(spot: &Spot) -> Option { }; hands.push(h.or_else(|| weg("mw range leer"))?); } - let game = GameM::build_passiv(order.len(), pot, cap, &[menu_fuer(&line, Menu3::standard()), later()], sl, passiv); + let menus = [menu_fuer(&line, Menu3::standard()), later()]; + let game = if linie() { GameM::build_linie(order.len(), pot, cap, &menus, sl, passiv, &line, me) } else { GameM::build_passiv(order.len(), pot, cap, &menus, sl, passiv) }; let at = if alle() { game.follow_nachsicht(&line, me) } else { game.follow(&line) }.or_else(|| weg("mw linie nicht im baum"))?; let NodeM::Dec { player, acts, .. } = &game.nodes[at] else { return weg("mw knoten") }; if *player != me { @@ -367,6 +496,28 @@ pub fn solve_multi3(spot: &Spot) -> Option { let combos: Vec = hands.iter().map(|h| h.masks.len()).collect(); let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?; let mut solver = SolverM::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15); + if pool_w() > 0.0 { + let masks: Vec<&[u64]> = (0..order.len()).map(|p| solver.masks(p)).collect(); + let sperren = pool_sperren(spot, &order, me, passiv, &masks, board, pot, cap, &|i| match &solver.game.nodes[i] { + NodeM::Dec { player, street: 0, acts, kids } => KnotenSicht::Dec { player: *player, acts, kids }, + _ => KnotenSicht::Ende, + }); + for (n, rows) in sperren { + solver.lock(n, rows, pool_w()); + } + } + if linie() { + let hands_n: Vec = (0..order.len()).map(|p| solver.masks(p).len()).collect(); + if let Some(pfad) = solver.game.pfad_nachsicht(&line, me) { + let sperren = linie_sperren(&pfad, me, &|n| match &solver.game.nodes[n] { + NodeM::Dec { player, acts, .. } => Some((*player, acts.len())), + _ => None, + }, &hands_n); + for (n, rows) in sperren { + solver.lock(n, rows, 1.0); + } + } + } let cpu_stufe = crate::engine::frist::thread_cpu_ms(); let mut done = 0u32; let mut zu_gross = false; @@ -404,6 +555,14 @@ pub fn solve_multi3(spot: &Spot) -> Option { if done < min_iter { return weg("mw zu wenig iterationen"); } + if std::env::var("KERN_REGRET").is_ok() { + eprintln!("regret chips {:?} hero_index {hero_index} combos {combos:?}", solver.regret_chips(at, hero_index)); + let mut v: Vec<(u32, String)> = (0..solver.masks(me).len()).map(|h| (fast7::score(solver.masks(me)[h] | board), format!("{:?}", solver.row(at, h).iter().map(|x| (x * 100.0).round() / 100.0).collect::>()))).collect(); + v.sort(); + for (sc, r) in v { + eprintln!(" score {sc} row {r}"); + } + } let row = solver.row(at, hero_index); return Some(SolvedM { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos }); } diff --git a/src/engine/river3_spieler.rs b/src/engine/river3_spieler.rs index 30709bc3..c3d1caa5 100644 --- a/src/engine/river3_spieler.rs +++ b/src/engine/river3_spieler.rs @@ -178,7 +178,8 @@ pub fn solve_river3(spot: &Spot) -> Option { }; hands.push(h.or_else(|| weg("mw range leer"))?); } - let game = Game3::build_passiv(order.len(), pot, cap, &crate::engine::multi3_spieler::menu_fuer(&line, Menu3::standard()), passiv); + let menu = crate::engine::multi3_spieler::menu_fuer(&line, Menu3::standard()); + let game = if crate::engine::multi3_spieler::linie() { Game3::build_linie(order.len(), pot, cap, &menu, passiv, &line, me) } else { Game3::build_passiv(order.len(), pot, cap, &menu, passiv) }; let at = if crate::engine::multi3_spieler::alle() { game.follow_nachsicht(&line, me) } else { game.follow(&line) }.or_else(|| weg("mw linie nicht im baum"))?; let Node3::Dec { player, acts, .. } = &game.nodes[at] else { return weg("mw knoten") }; if *player != me { @@ -189,6 +190,29 @@ pub fn solve_river3(spot: &Spot) -> Option { let combos: Vec = hands.iter().map(|h| h.masks.len()).collect(); let hero_index = hands[me].masks.iter().position(|m| *m == hero_mask)?; let mut solver = Solver3::new(game, hands, board, spot.seed ^ 0x9e37_79b9_7f4a_7c15); + let w = crate::engine::multi3_spieler::pool_w(); + if w > 0.0 { + let masks: Vec<&[u64]> = (0..order.len()).map(|p| solver.masks(p)).collect(); + let sperren = crate::engine::multi3_spieler::pool_sperren(spot, &order, me, passiv, &masks, board, pot, cap, &|i| match &solver.game.nodes[i] { + Node3::Dec { player, acts, kids } => crate::engine::multi3_spieler::KnotenSicht::Dec { player: *player, acts, kids }, + Node3::Term { .. } => crate::engine::multi3_spieler::KnotenSicht::Ende, + }); + for (n, rows) in sperren { + solver.lock(n, rows, w); + } + } + if crate::engine::multi3_spieler::linie() { + let hands_n: Vec = (0..order.len()).map(|p| solver.masks(p).len()).collect(); + if let Some(pfad) = solver.game.pfad_nachsicht(&line, me) { + let sperren = crate::engine::multi3_spieler::linie_sperren(&pfad, me, &|n| match &solver.game.nodes[n] { + Node3::Dec { player, acts, .. } => Some((*player, acts.len())), + _ => None, + }, &hands_n); + for (n, rows) in sperren { + solver.lock(n, rows, 1.0); + } + } + } let mut done = 0u32; while done < ITERS { solver.iterate(); @@ -200,10 +224,38 @@ pub fn solve_river3(spot: &Spot) -> Option { if done < MIN_ITERS { return crate::engine::multi3_spieler::weg("mw zu wenig iterationen"); } + if std::env::var("KERN_REGRET").is_ok() { + eprintln!("regret chips {:?}", solver.regret_chips(at, hero_index)); + let n = solver.masks(me).len(); + let mut v: Vec = (0..n).map(|h| solver.regret_chips(at, h).iter().fold(0.0f64, |m, x| m.max(x.abs()))).collect(); + v.sort_by(f64::total_cmp); + eprintln!("max |regret| je Hand (sortiert) {:?}", v); + } let row = solver.row(at, hero_index); Some(Solved3 { row, acts, iterations: solver.iterations(), millis: started.elapsed().as_secs_f64() * 1e3, players: order.len(), nodes, combos }) } +/// Diagnosis only (`kern_zeile`): per player (acting order) the model combos' showdown scores against hero's, `(better, tie, worse)` counts. +pub fn debug_bereiche(spot: &Spot) -> Option> { + let order = acting_order(spot)?; + let board = fast7::mask(&spot.board); + let hero_mask = fast7::mask(&spot.hero_cards); + let hs = fast7::score(hero_mask | board); + let mut out = Vec::new(); + for seat in &order { + let v = if *seat == spot.hero_seat { Villain { seat: *seat, stack: spot.hero_stack, folded: false, profile: None } } else { spot.live_villains().find(|v| v.seat == *seat)?.clone() }; + let h = model_hands(spot, &v, board, if *seat == spot.hero_seat { Some(hero_mask) } else { None }, MAX_COMBOS)?; + let (mut b, mut t, mut w) = (0, 0, 0); + for m in &h.masks { + if m & hero_mask != 0 { continue; } + let s = fast7::score(m | board); + if s > hs { b += 1 } else if s == hs { t += 1 } else { w += 1 } + } + out.push((*seat, h.masks.len(), b, t, w)); + } + Some(out) +} + /// The live multiway-river decision, or `None` and the heuristic keeps it. pub fn river3_decision(raw: &Spot) -> Option { if !river3() || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 || raw.live_villains().count() < 2 { diff --git a/src/engine/solver_kern.rs b/src/engine/solver_kern.rs index 3af86743..bea4e554 100644 --- a/src/engine/solver_kern.rs +++ b/src/engine/solver_kern.rs @@ -269,12 +269,12 @@ fn interp(k: &[(f64, f64)], r: f64) -> f64 { /// Teil A `river|`, 19.10.–16.11., n ≥ 37 000 je Fach); All-in: 0. const RAISE_POOL: [(f64, f64); 8] = [(0.20, 0.21), (0.33, 0.143), (0.48, 0.11), (0.62, 0.095), (0.77, 0.086), (0.97, 0.079), (1.3, 0.066), (2.0, 0.047)]; -fn raise_pool(r: f64) -> f64 { +pub(crate) fn raise_pool(r: f64) -> f64 { interp(&RAISE_POOL, r) } /// Weicher Übergang: Anteil `share` am unteren (`von_unten`) Ende der Range, Breite `h` im Perzentil. -fn rampe(q: f64, share: f64, h: f64, von_unten: bool) -> f64 { +pub(crate) fn rampe(q: f64, share: f64, h: f64, von_unten: bool) -> f64 { if share <= 0.0 { return 0.0; }