Skip to main content

jevrs_core/
question.rs

1use alloc::{string::String, vec::Vec};
2use core::marker::PhantomData;
3
4use crate::{Confidence, Levels, Options, Probability};
5
6#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
7fn nearest_index(expected: f64, maximum: usize) -> usize {
8    ((expected + 0.5) as usize).min(maximum)
9}
10
11/// Binds a question marker to the answer type returned for it.
12///
13/// Implement this only for a custom builder integration. The built-in marker
14/// types cover every Jev question kind.
15pub trait Question: 'static {
16    /// Selects the answer type that a [`Handle`](crate::Handle) retrieves.
17    type Answer: Send + Sync + 'static;
18}
19
20/// Marker to use for a yes/no question in a typed handle or [`QuestionSet`](crate::QuestionSet).
21#[derive(Clone, Copy, Debug, Default)]
22pub struct NoulQ;
23
24/// Marker to use when [`Options`] define a choice at compile time.
25///
26/// Use [`DynChoiceQ`] when options are supplied at runtime.
27#[derive(Clone, Copy, Debug)]
28pub struct ChoiceQ<O: Options>(PhantomData<O>);
29
30/// Marker to use when [`Levels`] define a score scale at compile time.
31///
32/// Use [`DynScoreQ`] when levels are supplied at runtime.
33#[derive(Clone, Copy, Debug)]
34pub struct ScoreQ<L: Levels>(PhantomData<L>);
35
36/// Marker returned for a choice built with runtime-defined [`crate::DynOptions`].
37///
38/// Use [`ChoiceQ`] for static options.
39#[derive(Clone, Copy, Debug, Default)]
40pub struct DynChoiceQ;
41
42/// Marker returned for a score built with runtime-defined [`crate::DynLevels`].
43///
44/// Use [`ScoreQ`] for static levels.
45#[derive(Clone, Copy, Debug, Default)]
46pub struct DynScoreQ;
47
48impl<O: Options> Default for ChoiceQ<O> {
49    fn default() -> Self {
50        Self(PhantomData)
51    }
52}
53
54impl<L: Levels> Default for ScoreQ<L> {
55    fn default() -> Self {
56        Self(PhantomData)
57    }
58}
59
60/// Readable alias to use for a yes/no field in a [`crate::QuestionSet`].
61pub type Noul = NoulQ;
62
63/// Readable alias to use for a static choice field in a [`crate::QuestionSet`].
64pub type Choice<O> = ChoiceQ<O>;
65
66/// Readable alias to use for a static score field in a [`crate::QuestionSet`].
67pub type Score<L> = ScoreQ<L>;
68
69impl Question for NoulQ {
70    type Answer = NoulAnswer;
71}
72
73impl<O: Options> Question for ChoiceQ<O> {
74    type Answer = ChoiceAnswer<O>;
75}
76
77impl<L: Levels> Question for ScoreQ<L> {
78    type Answer = ScoreAnswer<L>;
79}
80
81impl Question for DynChoiceQ {
82    type Answer = DynChoiceAnswer;
83}
84
85impl Question for DynScoreQ {
86    type Answer = DynScoreAnswer;
87}
88
89/// The probability assigned to a yes/no question's positive outcome.
90///
91/// Use [`Self::is_yes`] when your application has a decision threshold, or
92/// read [`Self::p`] when it needs the continuous probability.
93#[derive(Clone, Copy, Debug, PartialEq)]
94pub struct NoulAnswer {
95    /// Use this probability when ranking or displaying the positive outcome.
96    pub p: Probability,
97}
98
99impl NoulAnswer {
100    /// Applies an application-defined inclusive threshold to the probability.
101    #[must_use]
102    pub fn is_yes(&self, threshold: f64) -> bool {
103        self.p.get() >= threshold
104    }
105}
106
107/// The selected option and probability distribution for a static choice.
108///
109/// Use this typed result with [`ChoiceQ`]. Use [`DynChoiceAnswer`] when option
110/// keys were supplied at runtime.
111#[derive(Clone, Debug, PartialEq)]
112pub struct ChoiceAnswer<O: Options> {
113    /// Use the selected enum value for ordinary branching.
114    pub pick: O,
115    /// Use the full distribution when the winning option alone is insufficient.
116    pub probs: O::Map<Probability>,
117    /// Use this confidence to decide whether human review is needed.
118    pub confidence: Confidence,
119}
120
121/// The expected score and probability distribution for static levels.
122///
123/// Use this typed result with [`ScoreQ`]. Use [`DynScoreAnswer`] when level
124/// descriptions were supplied at runtime.
125#[derive(Clone, Debug, PartialEq)]
126pub struct ScoreAnswer<L: Levels> {
127    expected: f64,
128    /// Use the full distribution when expected or nearest level loses detail.
129    pub probs: L::Map<Probability>,
130    /// Use this confidence to decide whether human review is needed.
131    pub confidence: Confidence,
132}
133
134impl<L: Levels> ScoreAnswer<L> {
135    pub(crate) fn new(expected: f64, probs: L::Map<Probability>, confidence: Confidence) -> Self {
136        Self {
137            expected,
138            probs,
139            confidence,
140        }
141    }
142
143    /// Returns the fractional score when preserving model uncertainty matters.
144    #[must_use]
145    pub fn expected(&self) -> f64 {
146        self.expected
147    }
148
149    /// Returns a level when the fractional [`Self::expected`] must be bucketed.
150    #[must_use]
151    pub fn nearest(&self) -> L {
152        let index = nearest_index(self.expected, L::N.saturating_sub(1));
153        L::all()[index]
154    }
155
156    /// Returns the most probable level instead of rounding [`Self::expected`].
157    #[must_use]
158    pub fn argmax(&self) -> L {
159        let mut best = L::all()[0];
160        for &level in &L::all()[1..] {
161            if self.probs[level] > self.probs[best] {
162                best = level;
163            }
164        }
165        best
166    }
167}
168
169/// The selected option and probability distribution for a dynamic choice.
170///
171/// Use this with [`DynChoiceQ`] and runtime [`crate::DynOptions`]. Use
172/// [`ChoiceAnswer`] when an enum defines the choices.
173#[derive(Clone, Debug, PartialEq)]
174pub struct DynChoiceAnswer {
175    /// Use the selected runtime key for ordinary branching.
176    pub pick: String,
177    /// Use the ordered distribution when the winning key alone is insufficient.
178    pub probs: Vec<(String, Probability)>,
179    /// Use this confidence to decide whether human review is needed.
180    pub confidence: Confidence,
181}
182
183/// The expected score and probability distribution for dynamic levels.
184///
185/// Use this with [`DynScoreQ`] and runtime [`crate::DynLevels`]. Use
186/// [`ScoreAnswer`] when an enum defines the levels.
187#[derive(Clone, Debug, PartialEq)]
188pub struct DynScoreAnswer {
189    expected: f64,
190    /// Use this distribution with [`Self::legend`] to inspect every level.
191    pub probs: Vec<Probability>,
192    /// Use these descriptions to label [`Self::probs`] and returned indexes.
193    pub legend: Vec<String>,
194    /// Use this confidence to decide whether human review is needed.
195    pub confidence: Confidence,
196}
197
198impl DynScoreAnswer {
199    pub(crate) fn new(
200        expected: f64,
201        probs: Vec<Probability>,
202        legend: Vec<String>,
203        confidence: Confidence,
204    ) -> Self {
205        Self {
206            expected,
207            probs,
208            legend,
209            confidence,
210        }
211    }
212
213    /// Returns the fractional score when preserving model uncertainty matters.
214    #[must_use]
215    pub fn expected(&self) -> f64 {
216        self.expected
217    }
218
219    /// Returns an index when the fractional [`Self::expected`] must be bucketed.
220    #[must_use]
221    pub fn nearest(&self) -> usize {
222        nearest_index(self.expected, self.probs.len().saturating_sub(1))
223    }
224
225    /// Returns the most probable index instead of rounding [`Self::expected`].
226    #[must_use]
227    pub fn argmax(&self) -> usize {
228        let mut best = 0;
229        for index in 1..self.probs.len() {
230            if self.probs[index] > self.probs[best] {
231                best = index;
232            }
233        }
234        best
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use alloc::{string::ToString, vec};
241
242    use super::{DynScoreAnswer, NoulAnswer, ScoreAnswer};
243    use crate::{Confidence, Levels, Probability, test_support::Frustration};
244
245    fn probability(value: f64) -> Probability {
246        Probability::new(value).unwrap()
247    }
248
249    fn confidence() -> Confidence {
250        Confidence::new(0.9).unwrap()
251    }
252
253    #[test]
254    fn yes_threshold_is_inclusive() {
255        let answer = NoulAnswer {
256            p: probability(0.75),
257        };
258        assert!(answer.is_yes(0.74));
259        assert!(answer.is_yes(0.75));
260        assert!(!answer.is_yes(0.76));
261    }
262
263    #[test]
264    fn static_score_rounds_clamps_and_uses_first_argmax() {
265        let answer = ScoreAnswer::<Frustration>::new(
266            1.5,
267            Frustration::map_from_fn(|level| match level {
268                Frustration::Calm => probability(0.1),
269                Frustration::Frustrated | Frustration::VeryAngry => probability(0.45),
270            }),
271            confidence(),
272        );
273        assert!((answer.expected() - 1.5).abs() < f64::EPSILON);
274        assert_eq!(answer.nearest(), Frustration::VeryAngry);
275        assert_eq!(answer.argmax(), Frustration::Frustrated);
276
277        let clamped = ScoreAnswer::<Frustration>::new(
278            99.0,
279            Frustration::map_from_fn(|_| probability(0.0)),
280            confidence(),
281        );
282        assert_eq!(clamped.nearest(), Frustration::VeryAngry);
283    }
284
285    #[test]
286    fn dynamic_score_rounds_clamps_and_uses_first_argmax() {
287        let answer = DynScoreAnswer::new(
288            0.5,
289            vec![probability(0.1), probability(0.45), probability(0.45)],
290            vec!["Low".to_string(), "Medium".to_string(), "High".to_string()],
291            confidence(),
292        );
293        assert!((answer.expected() - 0.5).abs() < f64::EPSILON);
294        assert_eq!(answer.nearest(), 1);
295        assert_eq!(answer.argmax(), 1);
296
297        let clamped = DynScoreAnswer::new(
298            99.0,
299            vec![probability(0.5), probability(0.5)],
300            vec!["Low".to_string(), "High".to_string()],
301            confidence(),
302        );
303        assert_eq!(clamped.nearest(), 1);
304        assert_eq!(clamped.argmax(), 0);
305    }
306}