Skip to main content

native_solver/solver/
quality.rs

1//! Independent, exact strategy-quality reference for small heads-up trees.
2//!
3//! This deliberately does not call [`Trainer`](crate::Trainer) traversal, chance, blocker, or
4//! terminal kernels. It enumerates legal private deals, evaluates showdowns
5//! with [`evaluate_7`](crate::evaluate_7), and solves a separate decision problem for each own hand.
6//! Opponent states are summed **before** maximizing at an information set:
7//! a best response observes its own cards and public history, never the other
8//! player's cards. Public deals condition on both players' private cards.
9//!
10//! Only complete, singleton-card chance trees are supported. Suit-isomorphism
11//! representatives and sampled/incomplete chance trees are rejected. Both
12//! players may deviate independently per combo, even when the supplied policy
13//! was expanded from buckets. Thus this measures exploitability in the full
14//! private-card game on the supplied *betting tree*, not in a bucket-restricted
15//! game, and does not measure omitted bet sizes or other action-tree error.
16
17use super::chips::Chips;
18use super::tree::{Action, Node, Terminal};
19use crate::card::{bit, Card};
20use crate::eval::score_7;
21use std::collections::{HashMap, HashSet};
22use std::fmt;
23
24use crate::range::Combo;
25type Policy = HashMap<usize, Vec<Vec<f64>>>;
26
27/// Normalized quality of a fixed behavioral strategy profile.
28///
29/// All values are in chips, including half the initial pot in each player's
30/// invested baseline, as in [`Terminal`]. Expectations are over legal initial
31/// private deals with probability `w_oop * w_ip / joint_mass` and uniform legal
32/// runouts. `profile_ev` is the profile's value for each player;
33/// `best_response_ev[p]` holds the other player's policy fixed while player p
34/// deviates. NashConv is the sum of the two unilateral gains, and exploitability
35/// is NashConv / 2. For this zero-sum game NashConv also equals the sum of BR EVs.
36/// No value is clipped to conceal numerical error or a negative gain.
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct StrategyQuality {
39    /// `[OOP, IP]` value of the supplied profile.
40    pub profile_ev: [f64; 2],
41    /// `[OOP, IP]` value of each player's best response to the other's policy.
42    pub best_response_ev: [f64; 2],
43    /// Sum of both players' gains from deviating to a best response.
44    pub nash_conv: f64,
45    /// `nash_conv / 2`.
46    pub exploitability: f64,
47    /// Unnormalized sum of products of compatible initial range weights.
48    pub joint_mass: f64,
49}
50
51/// Invalid or unsupported reference-evaluation input.
52#[derive(Clone, Debug, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum QualityError {
55    /// The initial board has duplicate or out-of-range cards, or an
56    /// unsupported length.
57    InvalidBoard(String),
58    /// A combo has invalid or repeated cards, or a weight is negative or
59    /// not finite.
60    InvalidRange {
61        /// The player index whose range was rejected (0 = OOP, 1 = IP).
62        player: usize,
63        /// What was wrong.
64        reason: String,
65    },
66    /// No legal pair of private hands has positive finite joint weight.
67    NoCompatibleDeals,
68    /// The tree is malformed for the given board.
69    InvalidTree(String),
70    /// A chance node groups several cards under one representative; expand
71    /// suit-isomorphism reduction first.
72    UnsupportedChanceReduction,
73    /// The supplied policy has the wrong shape or is not a distribution.
74    InvalidStrategy {
75        /// The decision node with the invalid policy.
76        node_id: usize,
77        /// What was wrong.
78        reason: String,
79    },
80    /// Evaluation produced a NaN or infinite value.
81    NonFiniteResult,
82}
83
84impl fmt::Display for QualityError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::InvalidBoard(reason) => write!(f, "invalid initial board: {reason}"),
88            Self::InvalidRange { player, reason } => write!(f, "invalid player {player} range: {reason}"),
89            Self::NoCompatibleDeals => write!(f, "legal private deals must have positive finite joint mass"),
90            Self::InvalidTree(reason) => write!(f, "invalid reference tree: {reason}"),
91            Self::UnsupportedChanceReduction => write!(f, "reference evaluation requires singleton chance classes; expand suit-isomorphism reduction first"),
92            Self::InvalidStrategy { node_id, reason } => write!(f, "invalid strategy at node {node_id}: {reason}"),
93            Self::NonFiniteResult => write!(f, "reference evaluation produced a nonfinite value"),
94        }
95    }
96}
97
98impl std::error::Error for QualityError {}
99
100/// An independent, exact evaluator of strategy quality for small trees.
101///
102/// It shares no traversal code with [`Trainer`](crate::Trainer), so it can check
103/// the trainer's results. Showdown comparisons are cached once per evaluator.
104/// Time and memory grow with the tree size times the number of private-hand
105/// pairs, so use it for small trees: tests, fixtures, and quality benchmarks.
106///
107/// # Examples
108///
109/// ```
110/// use native_solver::solver::quality::ReferenceEvaluator;
111/// use native_solver::{build_tree, Card, CardSet, Chips, GameConfig, Player, Range, Trainer, TrainerOptions};
112///
113/// let board = ["Ks", "Th", "7s", "4d", "2s"]
114///     .iter()
115///     .map(|card| card.parse())
116///     .collect::<Result<Vec<Card>, _>>()?;
117/// let dead = CardSet::from_cards(&board);
118/// let config = GameConfig::new(board.clone(), Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
119/// let ranges = ["AA,KQs", "QQ,JJ"].map(|r| r.parse::<Range>().unwrap().combos(dead));
120/// let mut trainer = Trainer::new(build_tree(&config)?, ranges, TrainerOptions::default())?;
121/// trainer.train(200);
122///
123/// // Check the trainer's exploitability against the independent reference.
124/// let game = trainer.game();
125/// let reference = ReferenceEvaluator::new(game.tree(), &board, Player::ALL.map(|p| game.combos(p)))?;
126/// let quality = reference.evaluate(|node| trainer.average_strategy(node))?;
127/// assert!((quality.exploitability - trainer.exploitability().total).abs() < 1e-9);
128/// # Ok::<(), Box<dyn std::error::Error>>(())
129/// ```
130pub struct ReferenceEvaluator<'a> {
131    root: &'a Node,
132    initial_board: &'a [Card],
133    combos: [&'a [Combo]; 2],
134    masks: [Vec<u64>; 2],
135    /// Row-major OOP x IP normalized joint prior; impossible pairs have zero.
136    prior: Vec<f64>,
137    joint_mass: f64,
138    decisions: Vec<(usize, usize, usize)>,
139    /// Row-major OOP x IP showdown ordering (-1, 0, 1) for each complete board.
140    outcomes: HashMap<u64, Vec<i8>>,
141}
142
143impl std::fmt::Debug for ReferenceEvaluator<'_> {
144    /// A summary: board, range sizes, decisions, and joint mass.
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.debug_struct("ReferenceEvaluator")
147            .field("initial_board", &self.initial_board)
148            .field("num_combos", &[self.combos[0].len(), self.combos[1].len()])
149            .field("num_decisions", &self.decisions.len())
150            .field("joint_mass", &self.joint_mass)
151            .finish_non_exhaustive()
152    }
153}
154
155impl<'a> ReferenceEvaluator<'a> {
156    /// Validate the board, ranges, and complete unreduced tree.
157    ///
158    /// Finite nonnegative weights need not sum to one or be at most one.
159    /// Board-blocked combos are accepted but excluded, as are conflicting
160    /// private pairs and zero-weight combos. Decision IDs must be unique
161    /// public histories. Terminal payoffs and action labels define the
162    /// supplied game; this checks structural integrity, not whether the
163    /// betting sequence follows NLHE rules.
164    ///
165    /// # Errors
166    /// Returns a [`QualityError`] for a board that is not 3–5 distinct cards,
167    /// duplicate or reversed combos, a combo holding one card twice,
168    /// nonfinite or negative weights, zero or nonfinite legal joint mass, a
169    /// malformed tree, or a suit-reduced chance node.
170    pub fn new(
171        root: &'a Node,
172        initial_board: &'a [Card],
173        combos: [&'a [Combo]; 2],
174    ) -> Result<Self, QualityError> {
175        if !(3..=5).contains(&initial_board.len()) {
176            return Err(QualityError::InvalidBoard("expected 3 to 5 cards".into()));
177        }
178        let mut board_mask = 0u64;
179        for &card in initial_board {
180            if board_mask & bit(card) != 0 {
181                return Err(QualityError::InvalidBoard("cards must be distinct".into()));
182            }
183            board_mask |= bit(card);
184        }
185        let mut masks = [Vec::new(), Vec::new()];
186        for player in 0..2 {
187            let mut seen = HashSet::new();
188            for &Combo {
189                cards: [a, b],
190                weight,
191            } in combos[player]
192            {
193                let reason = if a == b {
194                    Some("a combo must contain two distinct cards")
195                } else if !weight.is_finite() || weight < 0.0 {
196                    Some("range weights must be finite and nonnegative")
197                } else if !seen.insert((a.min(b), a.max(b))) {
198                    Some("duplicate private combo")
199                } else {
200                    None
201                };
202                if let Some(reason) = reason {
203                    return Err(QualityError::InvalidRange {
204                        player,
205                        reason: reason.into(),
206                    });
207                }
208                masks[player].push((bit(a)) | (bit(b)));
209            }
210        }
211        let mut prior = Vec::new();
212        for (i, a) in combos[0].iter().enumerate() {
213            for (j, b) in combos[1].iter().enumerate() {
214                let legal =
215                    (masks[0][i] | masks[1][j]) & board_mask == 0 && masks[0][i] & masks[1][j] == 0;
216                prior.push(if legal { a.weight * b.weight } else { 0.0 });
217            }
218        }
219        let joint_mass: f64 = prior.iter().sum();
220        if !joint_mass.is_finite() || joint_mass <= 0.0 {
221            return Err(QualityError::NoCompatibleDeals);
222        }
223        for probability in &mut prior {
224            *probability /= joint_mass;
225        }
226        let mut evaluator = Self {
227            root,
228            initial_board,
229            combos,
230            masks,
231            prior,
232            joint_mass,
233            decisions: Vec::new(),
234            outcomes: HashMap::new(),
235        };
236        evaluator.validate_tree(root, &mut initial_board.to_vec(), &mut HashSet::new(), 0)?;
237        Ok(evaluator)
238    }
239
240    /// Measures the profile given by `strategy`: its EVs and exploitability.
241    ///
242    /// `strategy` is called once per decision node and returns
243    /// `[action][combo]` probabilities in the input range order, for example
244    /// `|id| trainer.average_strategy(id)`.
245    ///
246    /// Every column, including unreachable/blocked columns, must have finite
247    /// probabilities in [0, 1] summing to one within 1e-10. Accepted roundoff is
248    /// normalized to exactly one. The callback is not consulted during BR
249    /// search, and no trainer state or regret tables are read or modified.
250    ///
251    /// # Errors
252    /// Returns [`QualityError::InvalidStrategy`] for a strategy with the
253    /// wrong shape or a column that is not a distribution, and
254    /// [`QualityError::NonFiniteResult`] if evaluation overflows.
255    pub fn evaluate<F>(&self, mut strategy: F) -> Result<StrategyQuality, QualityError>
256    where
257        F: FnMut(usize) -> Vec<Vec<f64>>,
258    {
259        let mut policies = HashMap::new();
260        for &(id, player, actions) in &self.decisions {
261            let mut policy = strategy(id);
262            let invalid = |reason: &str| QualityError::InvalidStrategy {
263                node_id: id,
264                reason: reason.into(),
265            };
266            if policy.len() != actions
267                || policy
268                    .iter()
269                    .any(|row| row.len() != self.combos[player].len())
270            {
271                return Err(invalid("expected [action][combo] dimensions"));
272            }
273            for combo in 0..self.combos[player].len() {
274                let sum: f64 = policy.iter().map(|row| row[combo]).sum();
275                if policy
276                    .iter()
277                    .any(|row| !row[combo].is_finite() || !(0.0..=1.0).contains(&row[combo]))
278                    || !sum.is_finite()
279                    || (sum - 1.0).abs() > 1e-10
280                {
281                    return Err(invalid(
282                        "probability columns must be finite, nonnegative, and sum to one",
283                    ));
284                }
285                for row in &mut policy {
286                    row[combo] /= sum;
287                }
288            }
289            policies.insert(id, policy);
290        }
291        let mut profile_ev = [0.0; 2];
292        let mut best_response_ev = [0.0; 2];
293        let board_mask = mask(self.initial_board);
294        for player in 0..2 {
295            for own in 0..self.combos[player].len() {
296                let reach: Vec<f64> = (0..self.combos[1 - player].len())
297                    .map(|opp| self.prior[self.pair_index(player, own, opp)])
298                    .collect();
299                if reach.iter().all(|&weight| weight == 0.0) {
300                    continue;
301                }
302                let problem = PrivateProblem {
303                    evaluator: self,
304                    policies: &policies,
305                    player,
306                    own,
307                };
308                profile_ev[player] += problem.value(self.root, board_mask, &reach, false);
309                best_response_ev[player] += problem.value(self.root, board_mask, &reach, true);
310            }
311        }
312        let nash_conv =
313            (best_response_ev[0] - profile_ev[0]) + (best_response_ev[1] - profile_ev[1]);
314        let result = StrategyQuality {
315            profile_ev,
316            best_response_ev,
317            nash_conv,
318            exploitability: nash_conv / 2.0,
319            joint_mass: self.joint_mass,
320        };
321        if profile_ev
322            .iter()
323            .chain(&best_response_ev)
324            .chain([&nash_conv])
325            .any(|x| !x.is_finite())
326        {
327            return Err(QualityError::NonFiniteResult);
328        }
329        Ok(result)
330    }
331
332    fn pair_index(&self, player: usize, own: usize, opp: usize) -> usize {
333        if player == 0 {
334            own * self.combos[1].len() + opp
335        } else {
336            opp * self.combos[1].len() + own
337        }
338    }
339
340    fn validate_tree(
341        &mut self,
342        node: &Node,
343        board: &mut Vec<Card>,
344        ids: &mut HashSet<usize>,
345        depth: usize,
346    ) -> Result<(), QualityError> {
347        let invalid = |reason: &str| QualityError::InvalidTree(reason.into());
348        if depth > 256 {
349            return Err(invalid("reference traversal depth exceeds 256"));
350        }
351        match node {
352            Node::Decision {
353                id,
354                player,
355                actions,
356                children,
357            } => {
358                if actions.is_empty() || actions.len() != children.len() {
359                    return Err(invalid(
360                        "decisions need matching nonempty actions and children",
361                    ));
362                }
363                if !ids.insert(*id) {
364                    return Err(invalid("decision IDs must be unique public histories"));
365                }
366                if actions.iter().any(|action| matches!(action, Action::Bet(amount) | Action::Raise(amount) if *amount <= Chips::ZERO)) {
367                    return Err(invalid("bet and raise amounts must be positive"));
368                }
369                self.decisions.push((*id, player.index(), actions.len()));
370                for child in children {
371                    self.validate_tree(child, board, ids, depth + 1)?;
372                }
373            }
374            Node::Chance { children } => {
375                if board.len() >= 5 {
376                    return Err(invalid("cannot deal past a five-card board"));
377                }
378                if children.iter().any(|(members, _)| members.len() > 1) {
379                    return Err(QualityError::UnsupportedChanceReduction);
380                }
381                if children.len() != 52 - board.len() {
382                    return Err(invalid(
383                        "chance must enumerate every card outside the public board",
384                    ));
385                }
386                let mut seen = mask(board);
387                for (members, child) in children {
388                    if members.len() != 1 || seen & bit(members[0]) != 0 {
389                        return Err(invalid(
390                            "chance cards must be distinct singletons outside the public board",
391                        ));
392                    }
393                    seen |= bit(members[0]);
394                    board.push(members[0]);
395                    self.validate_tree(child, board, ids, depth + 1)?;
396                    board.pop();
397                }
398            }
399            Node::Terminal(terminal) => {
400                let invested = match terminal {
401                    Terminal::Fold { invested, .. } | Terminal::Showdown { invested } => invested,
402                };
403                if invested
404                    .iter()
405                    .any(|amount| !amount.is_finite() || *amount < 0.0)
406                {
407                    return Err(invalid(
408                        "terminal investments must be finite and nonnegative",
409                    ));
410                }
411                if matches!(terminal, Terminal::Showdown { .. }) {
412                    if board.len() != 5 {
413                        return Err(invalid("showdown requires a complete five-card board"));
414                    }
415                    self.cache_outcomes(board);
416                }
417            }
418        }
419        Ok(())
420    }
421
422    fn cache_outcomes(&mut self, board: &[Card]) {
423        let board_mask = mask(board);
424        self.outcomes.entry(board_mask).or_insert_with(|| {
425            let scores: [Vec<Option<u32>>; 2] = std::array::from_fn(|player| {
426                self.combos[player]
427                    .iter()
428                    .enumerate()
429                    .map(|(i, &Combo { cards: [a, b], .. })| {
430                        (self.masks[player][i] & board_mask == 0).then(|| {
431                            score_7([a, b, board[0], board[1], board[2], board[3], board[4]])
432                        })
433                    })
434                    .collect()
435            });
436            let mut outcomes = Vec::new();
437            for (i, a) in scores[0].iter().enumerate() {
438                for (j, b) in scores[1].iter().enumerate() {
439                    outcomes.push(match (a, b) {
440                        (Some(a), Some(b)) if self.masks[0][i] & self.masks[1][j] == 0 => {
441                            match a.cmp(b) {
442                                std::cmp::Ordering::Less => -1,
443                                std::cmp::Ordering::Equal => 0,
444                                std::cmp::Ordering::Greater => 1,
445                            }
446                        }
447                        _ => 0, // Impossible pairs have zero prior/reach.
448                    });
449                }
450            }
451            outcomes
452        });
453    }
454}
455
456struct PrivateProblem<'a, 'b> {
457    evaluator: &'b ReferenceEvaluator<'a>,
458    policies: &'b Policy,
459    player: usize,
460    own: usize,
461}
462
463impl PrivateProblem<'_, '_> {
464    fn value(&self, node: &Node, board: u64, reach: &[f64], best_response: bool) -> f64 {
465        if reach.iter().all(|&weight| weight == 0.0) {
466            return 0.0;
467        }
468        match node {
469            Node::Terminal(terminal) => reach
470                .iter()
471                .enumerate()
472                .map(|(opp, &weight)| {
473                    if weight == 0.0 {
474                        return 0.0;
475                    }
476                    let payoff = match terminal {
477                        Terminal::Fold { winner, invested } => {
478                            if winner.index() == self.player {
479                                invested[1 - self.player]
480                            } else {
481                                -invested[self.player]
482                            }
483                        }
484                        Terminal::Showdown { invested } => {
485                            let oop_order = self.evaluator.outcomes[&board]
486                                [self.evaluator.pair_index(self.player, self.own, opp)];
487                            let own_order = if self.player == 0 {
488                                oop_order
489                            } else {
490                                -oop_order
491                            };
492                            match own_order {
493                                1 => invested[1 - self.player],
494                                -1 => -invested[self.player],
495                                _ => (invested[1 - self.player] - invested[self.player]) / 2.0,
496                            }
497                        }
498                    };
499                    weight * payoff
500                })
501                .sum(),
502            Node::Chance { children } => {
503                // A fixed legal private pair removes four additional cards.
504                // Carry the branch probability in each hidden opponent state,
505                // preserving its posterior for every subsequent decision.
506                let probability = 1.0 / (52 - board.count_ones() - 4) as f64;
507                children
508                    .iter()
509                    .map(|(members, child)| {
510                        let card = bit(members[0]);
511                        if self.evaluator.masks[self.player][self.own] & card != 0 {
512                            return 0.0;
513                        }
514                        let next: Vec<f64> = reach
515                            .iter()
516                            .enumerate()
517                            .map(|(opp, &weight)| {
518                                if self.evaluator.masks[1 - self.player][opp] & card == 0 {
519                                    weight * probability
520                                } else {
521                                    0.0
522                                }
523                            })
524                            .collect();
525                        self.value(child, board | card, &next, best_response)
526                    })
527                    .sum()
528            }
529            Node::Decision {
530                id,
531                player,
532                children,
533                ..
534            } => {
535                let policy = &self.policies[id];
536                if player.index() == self.player {
537                    let values = children
538                        .iter()
539                        .map(|child| self.value(child, board, reach, best_response));
540                    if best_response {
541                        // One action per own hand/public history, after summing
542                        // every opponent state. A per-pair max is clairvoyance.
543                        values.fold(f64::NEG_INFINITY, f64::max)
544                    } else {
545                        values
546                            .enumerate()
547                            .map(|(action, value)| policy[action][self.own] * value)
548                            .sum()
549                    }
550                } else {
551                    children
552                        .iter()
553                        .enumerate()
554                        .map(|(action, child)| {
555                            let next: Vec<f64> = reach
556                                .iter()
557                                .enumerate()
558                                .map(|(opp, &weight)| weight * policy[action][opp])
559                                .collect();
560                            self.value(child, board, &next, best_response)
561                        })
562                        .sum()
563                }
564            }
565        }
566    }
567}
568
569fn mask(cards: &[Card]) -> u64 {
570    cards.iter().fold(0, |mask, &card| mask | (bit(card)))
571}