Skip to main content

native_solver/
range.rs

1//! Hand ranges: the standard 169 canonical starting hands (e.g. "AKs",
2//! "AKo", "AA"), each with a weight in `0.0..=1.0`, expandable into
3//! concrete card-pair combos with dead-card removal applied.
4
5use crate::card::{bit, Card, CardSet, RANKS};
6use std::collections::HashMap;
7use std::fmt;
8use std::str::FromStr;
9
10/// Why a range spec or hand weight was rejected.
11#[derive(Debug, Clone, PartialEq)]
12#[non_exhaustive]
13pub enum RangeError {
14    /// A `hand:weight` token whose weight is not a number.
15    InvalidWeight {
16        /// The whole `hand:weight` token as written.
17        token: String,
18    },
19    /// A weight that is not finite or lies outside `0.0..=1.0`.
20    WeightOutOfRange(f64),
21    /// Two different ranks without an `s`/`o` marker, e.g. `AK`.
22    NotAPair(String),
23    /// A pair with an `s`/`o` marker, e.g. `AAs`.
24    PairWithMarker(String),
25    /// A third character other than `s` or `o`.
26    InvalidMarker(String),
27    /// A rank character other than `23456789TJQKA`.
28    InvalidRank(char),
29    /// Anything else that is not canonical hand notation.
30    InvalidNotation(String),
31}
32
33impl fmt::Display for RangeError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Self::InvalidWeight { token } => write!(f, "invalid weight in '{token}'"),
37            Self::WeightOutOfRange(_) => {
38                write!(f, "range weight must be finite and between 0 and 1")
39            }
40            Self::NotAPair(hand) => {
41                write!(f, "'{hand}' is not a pair; did you mean to add 's' or 'o'?")
42            }
43            Self::PairWithMarker(hand) => {
44                write!(f, "pair '{hand}' cannot have a suited/offsuit marker")
45            }
46            Self::InvalidMarker(hand) => write!(f, "invalid suited/offsuit marker in '{hand}'"),
47            Self::InvalidRank(c) => write!(f, "invalid rank char: {c}"),
48            Self::InvalidNotation(hand) => write!(f, "invalid hand notation: '{hand}'"),
49        }
50    }
51}
52
53impl std::error::Error for RangeError {}
54
55/// One concrete two-card starting hand and its weight in a range.
56///
57/// # Examples
58///
59/// ```
60/// use native_solver::{Card, CardSet, Combo};
61///
62/// let card = |s: &str| s.parse::<Card>();
63/// let combo = Combo::new(card("Kd")?, card("Ks")?, 0.5);
64/// assert!(combo.conflicts_with(CardSet::from(card("Ks")?)));
65/// assert!(!combo.conflicts_with(CardSet::from(card("Kh")?)));
66/// # Ok::<(), Box<dyn std::error::Error>>(())
67/// ```
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub struct Combo {
70    /// The two hole cards, in no guaranteed order.
71    pub cards: [Card; 2],
72    /// The combo's weight in its range; only ratios within one range matter.
73    ///
74    /// [`Range::combos`] yields weights in `0.0..=1.0`; the trainer accepts
75    /// any finite, nonnegative weight.
76    pub weight: f64,
77}
78
79impl Combo {
80    /// A combo of two distinct cards; their order is kept as given.
81    pub fn new(first: Card, second: Card, weight: f64) -> Self {
82        Self {
83            cards: [first, second],
84            weight,
85        }
86    }
87
88    /// The two cards as a set, for dead-card and blocker checks.
89    pub fn mask(&self) -> CardSet {
90        CardSet(self.bits())
91    }
92
93    /// [`mask`](Self::mask) as a raw bitmask, for the solver's hot paths.
94    pub(crate) fn bits(&self) -> u64 {
95        bit(self.cards[0]) | bit(self.cards[1])
96    }
97
98    /// Whether the combo shares a card with `cards`.
99    pub fn conflicts_with(&self, cards: CardSet) -> bool {
100        !self.mask().is_disjoint(cards)
101    }
102
103    /// The cards ordered low then high, so equal hands compare equal
104    /// regardless of the order their cards were given in.
105    pub fn sorted_cards(&self) -> (Card, Card) {
106        let [a, b] = self.cards;
107        (a.min(b), a.max(b))
108    }
109}
110
111/// A weighted preflop range, keyed by canonical hand notation.
112///
113/// Parse one from text with [`str::parse`] (or [`Range::parse`]); its
114/// [`Display`](fmt::Display) form parses back to the same range.
115///
116/// ```
117/// use native_solver::{Card, CardSet, Range};
118///
119/// let range: Range = "AA, AKs, QJo:0.5".parse()?;
120/// assert_eq!(range.weight("AKs"), 1.0);
121/// assert_eq!(range.weight("JQo"), 0.5); // any rank order and case
122/// assert_eq!(range.to_string(), "AA,AKs,QJo:0.5");
123///
124/// // Expand into combos, dropping those that use a dead card.
125/// let dead = CardSet::from_cards(&["As".parse::<Card>()?]);
126/// assert_eq!(range.combos(dead).len(), 3 + 3 + 12);
127/// # Ok::<(), Box<dyn std::error::Error>>(())
128/// ```
129#[derive(Debug, Clone, Default, PartialEq)]
130pub struct Range {
131    weights: HashMap<String, f64>,
132}
133
134impl Range {
135    /// An empty range: every hand has weight `0.0`.
136    pub fn new() -> Self {
137        Self::default()
138    }
139
140    /// Parses a comma-separated range, e.g. `"AA,AKs,AQo:0.5,72o"`.
141    ///
142    /// A hand without a `:weight` suffix gets weight `1.0`. Same as
143    /// `spec.parse::<Range>()`.
144    ///
145    /// # Errors
146    /// Returns a [`RangeError`] for a hand that is not canonical notation
147    /// (two ranks, plus `s` or `o` when they differ) or a weight that is not
148    /// a number in `0.0..=1.0`.
149    pub fn parse(spec: &str) -> Result<Self, RangeError> {
150        let mut range = Range::new();
151        for token in spec.split(',') {
152            let token = token.trim();
153            if token.is_empty() {
154                continue;
155            }
156            let (hand, weight) = match token.split_once(':') {
157                Some((h, w)) => (
158                    h.trim(),
159                    w.trim()
160                        .parse::<f64>()
161                        .map_err(|_| RangeError::InvalidWeight {
162                            token: token.into(),
163                        })?,
164                ),
165                None => (token, 1.0),
166            };
167            range.set_weight(hand, weight)?;
168        }
169        Ok(range)
170    }
171
172    /// Sets the weight of a hand in canonical notation.
173    ///
174    /// The hand is written like "AA", "AKs", or "72o", in any rank order and
175    /// case. A weight of `0.0` removes the hand.
176    ///
177    /// # Errors
178    /// Returns a [`RangeError`] if `hand` is not canonical notation or
179    /// `weight` is not in `0.0..=1.0`.
180    pub fn set_weight(&mut self, hand: &str, weight: f64) -> Result<(), RangeError> {
181        if !weight.is_finite() || !(0.0..=1.0).contains(&weight) {
182            return Err(RangeError::WeightOutOfRange(weight));
183        }
184        let canon = canonicalize(hand)?;
185        if weight == 0.0 {
186            self.weights.remove(&canon);
187        } else {
188            self.weights.insert(canon, weight);
189        }
190        Ok(())
191    }
192
193    /// The weight of a hand in canonical notation.
194    ///
195    /// Returns `0.0` if the hand is not in the range or the notation is
196    /// invalid.
197    pub fn weight(&self, hand: &str) -> f64 {
198        canonicalize(hand)
199            .ok()
200            .and_then(|c| self.weights.get(&c).copied())
201            .unwrap_or(0.0)
202    }
203
204    /// Expands the range into combos, dropping any that use a card in `dead`.
205    ///
206    /// Pass the board as `dead`. Removing other cards too breaks suit
207    /// symmetry, which [`Trainer::new`](crate::Trainer::new) requires with
208    /// suit isomorphism or flop and turn buckets.
209    ///
210    /// Combos are ordered by their lower card, then their higher card, so the
211    /// order, and every solver result that sums over it, is the same on every
212    /// run however the range was built.
213    pub fn combos(&self, dead: CardSet) -> Vec<Combo> {
214        let mut out = Vec::new();
215        for (hand, &weight) in &self.weights {
216            if weight <= 0.0 {
217                continue;
218            }
219            hand_combos(hand, weight, dead, &mut out);
220        }
221        out.sort_unstable_by_key(Combo::sorted_cards);
222        out
223    }
224}
225
226impl FromStr for Range {
227    type Err = RangeError;
228
229    /// See [`Range::parse`].
230    fn from_str(spec: &str) -> Result<Range, RangeError> {
231        Range::parse(spec)
232    }
233}
234
235impl fmt::Display for Range {
236    /// The hands in [`all_canonical_hands`] order, comma-separated, with a
237    /// `:weight` suffix unless the weight is `1`.
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        let mut first = true;
240        for hand in all_canonical_hands() {
241            let Some(&weight) = self.weights.get(&hand) else {
242                continue;
243            };
244            if !first {
245                f.write_str(",")?;
246            }
247            first = false;
248            f.write_str(&hand)?;
249            if weight != 1.0 {
250                write!(f, ":{weight}")?;
251            }
252        }
253        Ok(())
254    }
255}
256
257/// All 169 canonical hand strings (13 pairs, 78 suited, 78 offsuit).
258pub fn all_canonical_hands() -> Vec<String> {
259    let ranks = RANKS.as_bytes();
260    let mut out = Vec::with_capacity(169);
261    for i in (0..13u8).rev() {
262        for j in (0..13u8).rev() {
263            if i == j {
264                let c = ranks[i as usize] as char;
265                out.push(format!("{c}{c}"));
266            } else if i > j {
267                let hi = ranks[i as usize] as char;
268                let lo = ranks[j as usize] as char;
269                out.push(format!("{hi}{lo}s"));
270                out.push(format!("{hi}{lo}o"));
271            }
272        }
273    }
274    out
275}
276
277fn rank_index(c: char) -> Result<u8, RangeError> {
278    RANKS
279        .find(c.to_ascii_uppercase())
280        .map(|i| i as u8)
281        .ok_or(RangeError::InvalidRank(c))
282}
283
284/// Normalize hand notation: uppercase ranks, high rank first, lowercase s/o suffix.
285fn canonicalize(hand: &str) -> Result<String, RangeError> {
286    let chars: Vec<char> = hand.chars().collect();
287    match chars.len() {
288        2 => {
289            let r1 = rank_index(chars[0])?;
290            let r2 = rank_index(chars[1])?;
291            if r1 != r2 {
292                return Err(RangeError::NotAPair(hand.into()));
293            }
294            let c = chars[0].to_ascii_uppercase();
295            Ok(format!("{c}{c}"))
296        }
297        3 => {
298            let r1 = rank_index(chars[0])?;
299            let r2 = rank_index(chars[1])?;
300            if r1 == r2 {
301                return Err(RangeError::PairWithMarker(hand.into()));
302            }
303            let marker = chars[2].to_ascii_lowercase();
304            if marker != 's' && marker != 'o' {
305                return Err(RangeError::InvalidMarker(hand.into()));
306            }
307            let (hi, lo) = if r1 >= r2 {
308                (chars[0], chars[1])
309            } else {
310                (chars[1], chars[0])
311            };
312            Ok(format!(
313                "{}{}{}",
314                hi.to_ascii_uppercase(),
315                lo.to_ascii_uppercase(),
316                marker
317            ))
318        }
319        _ => Err(RangeError::InvalidNotation(hand.into())),
320    }
321}
322
323fn hand_combos(canon: &str, weight: f64, dead: CardSet, out: &mut Vec<Combo>) {
324    let chars: Vec<char> = canon.chars().collect();
325    let push_if_alive = |c1: Card, c2: Card, out: &mut Vec<Combo>| {
326        if !dead.contains(c1) && !dead.contains(c2) {
327            out.push(Combo::new(c1, c2, weight));
328        }
329    };
330
331    if chars.len() == 2 {
332        let r = rank_index(chars[0]).expect("canonical hand has valid rank");
333        for s1 in 0..4u8 {
334            for s2 in (s1 + 1)..4u8 {
335                push_if_alive(Card(r * 4 + s1), Card(r * 4 + s2), out);
336            }
337        }
338        return;
339    }
340
341    let r1 = rank_index(chars[0]).expect("canonical hand has valid rank");
342    let r2 = rank_index(chars[1]).expect("canonical hand has valid rank");
343    let suited = chars[2] == 's';
344    if suited {
345        for s in 0..4u8 {
346            push_if_alive(Card(r1 * 4 + s), Card(r2 * 4 + s), out);
347        }
348    } else {
349        for s1 in 0..4u8 {
350            for s2 in 0..4u8 {
351                if s1 != s2 {
352                    push_if_alive(Card(r1 * 4 + s1), Card(r2 * 4 + s2), out);
353                }
354            }
355        }
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    /// `HashMap` iteration order differs between instances, so without the
364    /// sort two parses of the same spec could expand in different orders.
365    #[test]
366    fn combo_order_is_deterministic_and_sorted() {
367        let spec = "AA,KK:0.5,AKs,AQo,T9s,72o,JJ,QJs:0.25";
368        let dead =
369            CardSet::from_cards(&["Ah".parse::<Card>().unwrap(), "9s".parse::<Card>().unwrap()]);
370        let first = Range::parse(spec).unwrap().combos(dead);
371        for _ in 0..50 {
372            assert_eq!(Range::parse(spec).unwrap().combos(dead), first);
373        }
374        let keys: Vec<_> = first.iter().map(Combo::sorted_cards).collect();
375        assert!(
376            keys.windows(2).all(|pair| pair[0] < pair[1]),
377            "combos must be strictly ascending"
378        );
379    }
380
381    #[test]
382    fn pair_expands_to_six_combos() {
383        let range = Range::parse("AA").unwrap();
384        assert_eq!(range.combos(CardSet::EMPTY).len(), 6);
385    }
386
387    #[test]
388    fn suited_expands_to_four_combos() {
389        let range = Range::parse("AKs").unwrap();
390        assert_eq!(range.combos(CardSet::EMPTY).len(), 4);
391    }
392
393    #[test]
394    fn offsuit_expands_to_twelve_combos() {
395        let range = Range::parse("AKo").unwrap();
396        assert_eq!(range.combos(CardSet::EMPTY).len(), 12);
397    }
398
399    #[test]
400    fn full_range_has_1326_combos() {
401        let spec = all_canonical_hands().join(",");
402        let range = Range::parse(&spec).unwrap();
403        assert_eq!(all_canonical_hands().len(), 169);
404        assert_eq!(range.combos(CardSet::EMPTY).len(), 1326);
405    }
406
407    #[test]
408    fn dead_cards_remove_conflicting_combos() {
409        let range = Range::parse("AA").unwrap();
410        let dead = CardSet::from_cards(&["Ah".parse::<Card>().unwrap()]);
411        // One ace is dead, so only C(3,2) = 3 combos survive.
412        assert_eq!(range.combos(dead).len(), 3);
413    }
414
415    #[test]
416    fn canonicalize_ignores_input_order_and_case() {
417        let mut a = Range::new();
418        a.set_weight("KAs", 1.0).unwrap();
419        let mut b = Range::new();
420        b.set_weight("aks", 1.0).unwrap();
421        assert_eq!(a.weight("AKs"), 1.0);
422        assert_eq!(b.weight("AKs"), 1.0);
423    }
424
425    #[test]
426    fn display_round_trips_through_from_str() {
427        let range: Range = "QJo:0.5, aks, AA, 72o:0.25, KK:0".parse().unwrap();
428        assert_eq!(range.to_string(), "AA,AKs,QJo:0.5,72o:0.25");
429        assert_eq!(range.to_string().parse::<Range>().unwrap(), range);
430        let mut full = Range::new();
431        for hand in all_canonical_hands() {
432            full.set_weight(&hand, 0.3).unwrap();
433        }
434        assert_eq!(full.to_string().parse::<Range>().unwrap(), full);
435    }
436
437    #[test]
438    fn zero_weight_removes_a_hand() {
439        let mut range: Range = "AA,KK".parse().unwrap();
440        range.set_weight("KK", 0.0).unwrap();
441        assert_eq!(range, "AA".parse().unwrap());
442    }
443
444    #[test]
445    fn parses_per_hand_weights() {
446        let range = Range::parse("AA, AKo:0.5, 72o:0.25").unwrap();
447        assert_eq!(range.weight("AA"), 1.0);
448        assert_eq!(range.weight("AKo"), 0.5);
449        assert_eq!(range.weight("72o"), 0.25);
450        assert_eq!(range.weight("KK"), 0.0);
451    }
452
453    #[test]
454    fn whitespace_around_the_weight_separator_is_ignored() {
455        let range = Range::parse("AA : 0.5, AKs :0.25,QJo: 0.75").unwrap();
456        assert_eq!(range.weight("AA"), 0.5);
457        assert_eq!(range.weight("AKs"), 0.25);
458        assert_eq!(range.weight("QJo"), 0.75);
459    }
460
461    #[test]
462    fn rejects_invalid_hand_notation() {
463        assert_eq!(
464            Range::parse("AKq").unwrap_err(),
465            RangeError::InvalidMarker("AKq".into())
466        );
467        assert_eq!(
468            Range::parse("AAs").unwrap_err(),
469            RangeError::PairWithMarker("AAs".into())
470        );
471        assert_eq!(
472            Range::parse("AK").unwrap_err(),
473            RangeError::NotAPair("AK".into())
474        );
475        assert_eq!(
476            Range::parse("A").unwrap_err(),
477            RangeError::InvalidNotation("A".into())
478        );
479        assert_eq!(
480            Range::parse("AXs").unwrap_err(),
481            RangeError::InvalidRank('X')
482        );
483        assert_eq!(
484            Range::parse("AA:x").unwrap_err(),
485            RangeError::InvalidWeight {
486                token: "AA:x".into()
487            }
488        );
489    }
490
491    #[test]
492    fn rejects_invalid_weights_including_non_finite_values() {
493        for spec in ["AA:NaN", "AA:inf", "AA:-inf", "AA:-0.1", "AA:1.1"] {
494            assert!(Range::parse(spec).is_err(), "accepted {spec}");
495        }
496        assert!(Range::parse("AA:0,KK:1").is_ok());
497    }
498}