Skip to main content

zenpsy_api/
eval.rs

1//! Borrowed score views without prescribing native result storage.
2use alloc::borrow::Cow;
3/// Quality ordering; diagnostic features need not have one.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5#[non_exhaustive]
6pub enum Direction {
7    /// Higher indicates better quality.
8    Higher,
9    /// Lower indicates better quality.
10    Lower,
11    /// No quality ordering is defined.
12    Unordered,
13}
14/// Native output semantics, shared by scalars and maps. No universal range
15/// or normalization is imposed.
16#[derive(Clone, Debug, PartialEq)]
17#[non_exhaustive]
18pub struct ScoreSpec {
19    /// Stable identifier, unique within an assessment.
20    key: Cow<'static, str>,
21    /// Quality ordering.
22    direction: Direction,
23    /// Native unit or scale name.
24    unit: Cow<'static, str>,
25    /// Defined identical-pair value, if any.
26    perfect: Option<f64>,
27    /// Whether positive infinity is valid. NaN is never valid.
28    positive_infinity: bool,
29}
30impl ScoreSpec {
31    /// Declare a scalar without an assumed identity value or range.
32    pub const fn new(key: &'static str, direction: Direction) -> Self {
33        Self {
34            key: Cow::Borrowed(key),
35            direction,
36            unit: Cow::Borrowed(""),
37            perfect: None,
38            positive_infinity: false,
39        }
40    }
41    /// Replace the stable identifier, including a name computed at runtime.
42    pub fn with_key(mut self, key: impl Into<Cow<'static, str>>) -> Self {
43        self.key = key.into();
44        self
45    }
46    /// Stable output identifier.
47    pub fn key(&self) -> &str {
48        &self.key
49    }
50    /// Native quality ordering.
51    pub const fn direction(&self) -> Direction {
52        self.direction
53    }
54    /// Native unit or scale name.
55    pub fn unit(&self) -> &str {
56        &self.unit
57    }
58    /// Defined identical-pair value, if any.
59    pub const fn perfect(&self) -> Option<f64> {
60        self.perfect
61    }
62    /// Whether positive infinity is accepted as a scalar value.
63    pub const fn positive_infinity(&self) -> bool {
64        self.positive_infinity
65    }
66    /// Configure infinity independently of any identical-pair value.
67    pub const fn with_positive_infinity(mut self, allowed: bool) -> Self {
68        self.positive_infinity = allowed;
69        self
70    }
71    /// Name the native unit or scale.
72    pub fn with_unit(mut self, unit: impl Into<Cow<'static, str>>) -> Self {
73        self.unit = unit.into();
74        self
75    }
76    /// Set the identical-pair value, permitting positive infinity if specified.
77    ///
78    /// # Panics
79    /// Panics for NaN or negative infinity, which cannot be valid scores.
80    pub const fn with_perfect(mut self, value: f64) -> Self {
81        assert!(
82            !value.is_nan() && value != f64::NEG_INFINITY,
83            "invalid identical-pair value"
84        );
85        self.perfect = Some(value);
86        self.positive_infinity = value == f64::INFINITY;
87        self
88    }
89}
90/// Unmodified scalar with borrowed semantics.
91#[derive(Clone, Copy, Debug)]
92#[non_exhaustive]
93pub struct Score<'a> {
94    /// Scalar meaning.
95    pub spec: &'a ScoreSpec,
96    /// Native value.
97    pub value: f64,
98}
99impl<'a> Score<'a> {
100    /// Borrow a descriptor for a native value.
101    pub const fn new(spec: &'a ScoreSpec, value: f64) -> Self {
102        Self { spec, value }
103    }
104}
105/// Common access to a concrete assessment. Additional native fields remain
106/// accessible on its concrete type. Iteration need not allocate. A successful
107/// assessment has at least one uniquely named score, in stable output order.
108pub trait Evaluation {
109    /// All scalar outputs and their semantics, headline first when applicable.
110    fn scores(&self) -> impl Iterator<Item = Score<'_>>;
111    /// Visit scores without allocating an erased iterator. Implementations
112    /// overriding this method must expose exactly the same order and values.
113    fn visit_scores<'a>(&'a self, visitor: &mut dyn FnMut(Score<'a>)) {
114        self.scores().for_each(visitor);
115    }
116    /// Visit maps without allocating an erased iterator, with the same views
117    /// and order as [`Self::maps`].
118    fn visit_maps<'a>(&'a self, visitor: &mut dyn FnMut(crate::MapView<'a>)) {
119        self.maps().for_each(visitor);
120    }
121    /// Borrow native map planes when diagnostics were requested. The default
122    /// publishes none; a metric without diagnostics must refuse a request.
123    /// Native fields remain accessible even when no common map view is exposed.
124    fn maps(&self) -> impl Iterator<Item = crate::MapView<'_>> {
125        core::iter::empty()
126    }
127}
128
129/// A temporary assessment borrowed during a lending comparison. The view
130/// cannot outlive the callback or retain metric scratch. Native typed results
131/// remain available from the ordinary owned scoring interface.
132#[derive(Clone, Copy)]
133pub struct EvaluationRef<'a> {
134    inner: &'a dyn EvaluationAccess,
135}
136impl<'a> EvaluationRef<'a> {
137    /// Borrow a concrete assessment without boxing or copying its maps.
138    pub fn new<T: Evaluation>(value: &'a T) -> Self {
139        Self { inner: value }
140    }
141    /// Visit every named scalar in native output order.
142    pub fn visit_scores(self, mut visitor: impl FnMut(Score<'a>)) {
143        self.inner.visit_scores(&mut visitor);
144    }
145    /// Visit every native map in output order.
146    pub fn visit_maps(self, mut visitor: impl FnMut(crate::MapView<'a>)) {
147        self.inner.visit_maps(&mut visitor);
148    }
149}
150pub(crate) trait EvaluationAccess {
151    fn visit_scores<'a>(&'a self, visitor: &mut dyn FnMut(Score<'a>));
152    fn visit_maps<'a>(&'a self, visitor: &mut dyn FnMut(crate::MapView<'a>));
153}
154impl<T: Evaluation> EvaluationAccess for T {
155    fn visit_scores<'a>(&'a self, visitor: &mut dyn FnMut(Score<'a>)) {
156        Evaluation::visit_scores(self, visitor);
157    }
158    fn visit_maps<'a>(&'a self, visitor: &mut dyn FnMut(crate::MapView<'a>)) {
159        Evaluation::visit_maps(self, visitor);
160    }
161}