native-solver 0.1.0

Heads-up postflop No-Limit Hold'em solver: hand evaluator, ranges, betting trees, and combo-vectorized CFR / CFR+ / DCFR.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Hand ranges: the standard 169 canonical starting hands (e.g. "AKs",
//! "AKo", "AA"), each with a weight in `0.0..=1.0`, expandable into
//! concrete card-pair combos with dead-card removal applied.

use crate::card::{bit, Card, CardSet, RANKS};
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;

/// Why a range spec or hand weight was rejected.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum RangeError {
    /// A `hand:weight` token whose weight is not a number.
    InvalidWeight {
        /// The whole `hand:weight` token as written.
        token: String,
    },
    /// A weight that is not finite or lies outside `0.0..=1.0`.
    WeightOutOfRange(f64),
    /// Two different ranks without an `s`/`o` marker, e.g. `AK`.
    NotAPair(String),
    /// A pair with an `s`/`o` marker, e.g. `AAs`.
    PairWithMarker(String),
    /// A third character other than `s` or `o`.
    InvalidMarker(String),
    /// A rank character other than `23456789TJQKA`.
    InvalidRank(char),
    /// Anything else that is not canonical hand notation.
    InvalidNotation(String),
}

impl fmt::Display for RangeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidWeight { token } => write!(f, "invalid weight in '{token}'"),
            Self::WeightOutOfRange(_) => {
                write!(f, "range weight must be finite and between 0 and 1")
            }
            Self::NotAPair(hand) => {
                write!(f, "'{hand}' is not a pair; did you mean to add 's' or 'o'?")
            }
            Self::PairWithMarker(hand) => {
                write!(f, "pair '{hand}' cannot have a suited/offsuit marker")
            }
            Self::InvalidMarker(hand) => write!(f, "invalid suited/offsuit marker in '{hand}'"),
            Self::InvalidRank(c) => write!(f, "invalid rank char: {c}"),
            Self::InvalidNotation(hand) => write!(f, "invalid hand notation: '{hand}'"),
        }
    }
}

impl std::error::Error for RangeError {}

/// One concrete two-card starting hand and its weight in a range.
///
/// # Examples
///
/// ```
/// use native_solver::{Card, CardSet, Combo};
///
/// let card = |s: &str| s.parse::<Card>();
/// let combo = Combo::new(card("Kd")?, card("Ks")?, 0.5);
/// assert!(combo.conflicts_with(CardSet::from(card("Ks")?)));
/// assert!(!combo.conflicts_with(CardSet::from(card("Kh")?)));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Combo {
    /// The two hole cards, in no guaranteed order.
    pub cards: [Card; 2],
    /// The combo's weight in its range; only ratios within one range matter.
    ///
    /// [`Range::combos`] yields weights in `0.0..=1.0`; the trainer accepts
    /// any finite, nonnegative weight.
    pub weight: f64,
}

impl Combo {
    /// A combo of two distinct cards; their order is kept as given.
    pub fn new(first: Card, second: Card, weight: f64) -> Self {
        Self {
            cards: [first, second],
            weight,
        }
    }

    /// The two cards as a set, for dead-card and blocker checks.
    pub fn mask(&self) -> CardSet {
        CardSet(self.bits())
    }

    /// [`mask`](Self::mask) as a raw bitmask, for the solver's hot paths.
    pub(crate) fn bits(&self) -> u64 {
        bit(self.cards[0]) | bit(self.cards[1])
    }

    /// Whether the combo shares a card with `cards`.
    pub fn conflicts_with(&self, cards: CardSet) -> bool {
        !self.mask().is_disjoint(cards)
    }

    /// The cards ordered low then high, so equal hands compare equal
    /// regardless of the order their cards were given in.
    pub fn sorted_cards(&self) -> (Card, Card) {
        let [a, b] = self.cards;
        (a.min(b), a.max(b))
    }
}

/// A weighted preflop range, keyed by canonical hand notation.
///
/// Parse one from text with [`str::parse`] (or [`Range::parse`]); its
/// [`Display`](fmt::Display) form parses back to the same range.
///
/// ```
/// use native_solver::{Card, CardSet, Range};
///
/// let range: Range = "AA, AKs, QJo:0.5".parse()?;
/// assert_eq!(range.weight("AKs"), 1.0);
/// assert_eq!(range.weight("JQo"), 0.5); // any rank order and case
/// assert_eq!(range.to_string(), "AA,AKs,QJo:0.5");
///
/// // Expand into combos, dropping those that use a dead card.
/// let dead = CardSet::from_cards(&["As".parse::<Card>()?]);
/// assert_eq!(range.combos(dead).len(), 3 + 3 + 12);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Range {
    weights: HashMap<String, f64>,
}

impl Range {
    /// An empty range: every hand has weight `0.0`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Parses a comma-separated range, e.g. `"AA,AKs,AQo:0.5,72o"`.
    ///
    /// A hand without a `:weight` suffix gets weight `1.0`. Same as
    /// `spec.parse::<Range>()`.
    ///
    /// # Errors
    /// Returns a [`RangeError`] for a hand that is not canonical notation
    /// (two ranks, plus `s` or `o` when they differ) or a weight that is not
    /// a number in `0.0..=1.0`.
    pub fn parse(spec: &str) -> Result<Self, RangeError> {
        let mut range = Range::new();
        for token in spec.split(',') {
            let token = token.trim();
            if token.is_empty() {
                continue;
            }
            let (hand, weight) = match token.split_once(':') {
                Some((h, w)) => (
                    h.trim(),
                    w.trim()
                        .parse::<f64>()
                        .map_err(|_| RangeError::InvalidWeight {
                            token: token.into(),
                        })?,
                ),
                None => (token, 1.0),
            };
            range.set_weight(hand, weight)?;
        }
        Ok(range)
    }

    /// Sets the weight of a hand in canonical notation.
    ///
    /// The hand is written like "AA", "AKs", or "72o", in any rank order and
    /// case. A weight of `0.0` removes the hand.
    ///
    /// # Errors
    /// Returns a [`RangeError`] if `hand` is not canonical notation or
    /// `weight` is not in `0.0..=1.0`.
    pub fn set_weight(&mut self, hand: &str, weight: f64) -> Result<(), RangeError> {
        if !weight.is_finite() || !(0.0..=1.0).contains(&weight) {
            return Err(RangeError::WeightOutOfRange(weight));
        }
        let canon = canonicalize(hand)?;
        if weight == 0.0 {
            self.weights.remove(&canon);
        } else {
            self.weights.insert(canon, weight);
        }
        Ok(())
    }

    /// The weight of a hand in canonical notation.
    ///
    /// Returns `0.0` if the hand is not in the range or the notation is
    /// invalid.
    pub fn weight(&self, hand: &str) -> f64 {
        canonicalize(hand)
            .ok()
            .and_then(|c| self.weights.get(&c).copied())
            .unwrap_or(0.0)
    }

    /// Expands the range into combos, dropping any that use a card in `dead`.
    ///
    /// Pass the board as `dead`. Removing other cards too breaks suit
    /// symmetry, which [`Trainer::new`](crate::Trainer::new) requires with
    /// suit isomorphism or flop and turn buckets.
    ///
    /// Combos are ordered by their lower card, then their higher card, so the
    /// order, and every solver result that sums over it, is the same on every
    /// run however the range was built.
    pub fn combos(&self, dead: CardSet) -> Vec<Combo> {
        let mut out = Vec::new();
        for (hand, &weight) in &self.weights {
            if weight <= 0.0 {
                continue;
            }
            hand_combos(hand, weight, dead, &mut out);
        }
        out.sort_unstable_by_key(Combo::sorted_cards);
        out
    }
}

impl FromStr for Range {
    type Err = RangeError;

    /// See [`Range::parse`].
    fn from_str(spec: &str) -> Result<Range, RangeError> {
        Range::parse(spec)
    }
}

impl fmt::Display for Range {
    /// The hands in [`all_canonical_hands`] order, comma-separated, with a
    /// `:weight` suffix unless the weight is `1`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for hand in all_canonical_hands() {
            let Some(&weight) = self.weights.get(&hand) else {
                continue;
            };
            if !first {
                f.write_str(",")?;
            }
            first = false;
            f.write_str(&hand)?;
            if weight != 1.0 {
                write!(f, ":{weight}")?;
            }
        }
        Ok(())
    }
}

/// All 169 canonical hand strings (13 pairs, 78 suited, 78 offsuit).
pub fn all_canonical_hands() -> Vec<String> {
    let ranks = RANKS.as_bytes();
    let mut out = Vec::with_capacity(169);
    for i in (0..13u8).rev() {
        for j in (0..13u8).rev() {
            if i == j {
                let c = ranks[i as usize] as char;
                out.push(format!("{c}{c}"));
            } else if i > j {
                let hi = ranks[i as usize] as char;
                let lo = ranks[j as usize] as char;
                out.push(format!("{hi}{lo}s"));
                out.push(format!("{hi}{lo}o"));
            }
        }
    }
    out
}

fn rank_index(c: char) -> Result<u8, RangeError> {
    RANKS
        .find(c.to_ascii_uppercase())
        .map(|i| i as u8)
        .ok_or(RangeError::InvalidRank(c))
}

/// Normalize hand notation: uppercase ranks, high rank first, lowercase s/o suffix.
fn canonicalize(hand: &str) -> Result<String, RangeError> {
    let chars: Vec<char> = hand.chars().collect();
    match chars.len() {
        2 => {
            let r1 = rank_index(chars[0])?;
            let r2 = rank_index(chars[1])?;
            if r1 != r2 {
                return Err(RangeError::NotAPair(hand.into()));
            }
            let c = chars[0].to_ascii_uppercase();
            Ok(format!("{c}{c}"))
        }
        3 => {
            let r1 = rank_index(chars[0])?;
            let r2 = rank_index(chars[1])?;
            if r1 == r2 {
                return Err(RangeError::PairWithMarker(hand.into()));
            }
            let marker = chars[2].to_ascii_lowercase();
            if marker != 's' && marker != 'o' {
                return Err(RangeError::InvalidMarker(hand.into()));
            }
            let (hi, lo) = if r1 >= r2 {
                (chars[0], chars[1])
            } else {
                (chars[1], chars[0])
            };
            Ok(format!(
                "{}{}{}",
                hi.to_ascii_uppercase(),
                lo.to_ascii_uppercase(),
                marker
            ))
        }
        _ => Err(RangeError::InvalidNotation(hand.into())),
    }
}

fn hand_combos(canon: &str, weight: f64, dead: CardSet, out: &mut Vec<Combo>) {
    let chars: Vec<char> = canon.chars().collect();
    let push_if_alive = |c1: Card, c2: Card, out: &mut Vec<Combo>| {
        if !dead.contains(c1) && !dead.contains(c2) {
            out.push(Combo::new(c1, c2, weight));
        }
    };

    if chars.len() == 2 {
        let r = rank_index(chars[0]).expect("canonical hand has valid rank");
        for s1 in 0..4u8 {
            for s2 in (s1 + 1)..4u8 {
                push_if_alive(Card(r * 4 + s1), Card(r * 4 + s2), out);
            }
        }
        return;
    }

    let r1 = rank_index(chars[0]).expect("canonical hand has valid rank");
    let r2 = rank_index(chars[1]).expect("canonical hand has valid rank");
    let suited = chars[2] == 's';
    if suited {
        for s in 0..4u8 {
            push_if_alive(Card(r1 * 4 + s), Card(r2 * 4 + s), out);
        }
    } else {
        for s1 in 0..4u8 {
            for s2 in 0..4u8 {
                if s1 != s2 {
                    push_if_alive(Card(r1 * 4 + s1), Card(r2 * 4 + s2), out);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `HashMap` iteration order differs between instances, so without the
    /// sort two parses of the same spec could expand in different orders.
    #[test]
    fn combo_order_is_deterministic_and_sorted() {
        let spec = "AA,KK:0.5,AKs,AQo,T9s,72o,JJ,QJs:0.25";
        let dead =
            CardSet::from_cards(&["Ah".parse::<Card>().unwrap(), "9s".parse::<Card>().unwrap()]);
        let first = Range::parse(spec).unwrap().combos(dead);
        for _ in 0..50 {
            assert_eq!(Range::parse(spec).unwrap().combos(dead), first);
        }
        let keys: Vec<_> = first.iter().map(Combo::sorted_cards).collect();
        assert!(
            keys.windows(2).all(|pair| pair[0] < pair[1]),
            "combos must be strictly ascending"
        );
    }

    #[test]
    fn pair_expands_to_six_combos() {
        let range = Range::parse("AA").unwrap();
        assert_eq!(range.combos(CardSet::EMPTY).len(), 6);
    }

    #[test]
    fn suited_expands_to_four_combos() {
        let range = Range::parse("AKs").unwrap();
        assert_eq!(range.combos(CardSet::EMPTY).len(), 4);
    }

    #[test]
    fn offsuit_expands_to_twelve_combos() {
        let range = Range::parse("AKo").unwrap();
        assert_eq!(range.combos(CardSet::EMPTY).len(), 12);
    }

    #[test]
    fn full_range_has_1326_combos() {
        let spec = all_canonical_hands().join(",");
        let range = Range::parse(&spec).unwrap();
        assert_eq!(all_canonical_hands().len(), 169);
        assert_eq!(range.combos(CardSet::EMPTY).len(), 1326);
    }

    #[test]
    fn dead_cards_remove_conflicting_combos() {
        let range = Range::parse("AA").unwrap();
        let dead = CardSet::from_cards(&["Ah".parse::<Card>().unwrap()]);
        // One ace is dead, so only C(3,2) = 3 combos survive.
        assert_eq!(range.combos(dead).len(), 3);
    }

    #[test]
    fn canonicalize_ignores_input_order_and_case() {
        let mut a = Range::new();
        a.set_weight("KAs", 1.0).unwrap();
        let mut b = Range::new();
        b.set_weight("aks", 1.0).unwrap();
        assert_eq!(a.weight("AKs"), 1.0);
        assert_eq!(b.weight("AKs"), 1.0);
    }

    #[test]
    fn display_round_trips_through_from_str() {
        let range: Range = "QJo:0.5, aks, AA, 72o:0.25, KK:0".parse().unwrap();
        assert_eq!(range.to_string(), "AA,AKs,QJo:0.5,72o:0.25");
        assert_eq!(range.to_string().parse::<Range>().unwrap(), range);
        let mut full = Range::new();
        for hand in all_canonical_hands() {
            full.set_weight(&hand, 0.3).unwrap();
        }
        assert_eq!(full.to_string().parse::<Range>().unwrap(), full);
    }

    #[test]
    fn zero_weight_removes_a_hand() {
        let mut range: Range = "AA,KK".parse().unwrap();
        range.set_weight("KK", 0.0).unwrap();
        assert_eq!(range, "AA".parse().unwrap());
    }

    #[test]
    fn parses_per_hand_weights() {
        let range = Range::parse("AA, AKo:0.5, 72o:0.25").unwrap();
        assert_eq!(range.weight("AA"), 1.0);
        assert_eq!(range.weight("AKo"), 0.5);
        assert_eq!(range.weight("72o"), 0.25);
        assert_eq!(range.weight("KK"), 0.0);
    }

    #[test]
    fn whitespace_around_the_weight_separator_is_ignored() {
        let range = Range::parse("AA : 0.5, AKs :0.25,QJo: 0.75").unwrap();
        assert_eq!(range.weight("AA"), 0.5);
        assert_eq!(range.weight("AKs"), 0.25);
        assert_eq!(range.weight("QJo"), 0.75);
    }

    #[test]
    fn rejects_invalid_hand_notation() {
        assert_eq!(
            Range::parse("AKq").unwrap_err(),
            RangeError::InvalidMarker("AKq".into())
        );
        assert_eq!(
            Range::parse("AAs").unwrap_err(),
            RangeError::PairWithMarker("AAs".into())
        );
        assert_eq!(
            Range::parse("AK").unwrap_err(),
            RangeError::NotAPair("AK".into())
        );
        assert_eq!(
            Range::parse("A").unwrap_err(),
            RangeError::InvalidNotation("A".into())
        );
        assert_eq!(
            Range::parse("AXs").unwrap_err(),
            RangeError::InvalidRank('X')
        );
        assert_eq!(
            Range::parse("AA:x").unwrap_err(),
            RangeError::InvalidWeight {
                token: "AA:x".into()
            }
        );
    }

    #[test]
    fn rejects_invalid_weights_including_non_finite_values() {
        for spec in ["AA:NaN", "AA:inf", "AA:-inf", "AA:-0.1", "AA:1.1"] {
            assert!(Range::parse(spec).is_err(), "accepted {spec}");
        }
        assert!(Range::parse("AA:0,KK:1").is_ok());
    }
}