Skip to main content

zenpsy_api/
erased.rs

1//! Optional erasure at collection boundaries, preserving native results.
2use crate::{
3    EvalOpts, Evaluation, MapView, Metric, MetricId, MetricResult, NoReferenceMetric,
4    PrepareReference, PreparedReference, Score, WarmReference,
5};
6use alloc::boxed::Box;
7use core::any::{Any, TypeId};
8use zenpixels::PixelView;
9
10trait NativeEvaluation: crate::eval::EvaluationAccess {
11    fn scores(&self) -> Box<dyn Iterator<Item = Score<'_>> + '_>;
12    fn maps(&self) -> Box<dyn Iterator<Item = MapView<'_>> + '_>;
13    fn as_any(&self) -> &dyn Any;
14}
15impl<T: Evaluation + 'static> NativeEvaluation for T {
16    fn scores(&self) -> Box<dyn Iterator<Item = Score<'_>> + '_> {
17        Box::new(Evaluation::scores(self))
18    }
19    fn maps(&self) -> Box<dyn Iterator<Item = MapView<'_>> + '_> {
20        Box::new(Evaluation::maps(self))
21    }
22    fn as_any(&self) -> &dyn Any {
23        self
24    }
25}
26
27/// An owned native assessment with common borrowed score access. The native
28/// result is moved into a box; scalar descriptors and diagnostic arrays are not
29/// copied. Score iteration uses a short-lived erased iterator allocation.
30pub struct ErasedEvaluation {
31    inner: Box<dyn NativeEvaluation>,
32}
33impl ErasedEvaluation {
34    /// Erase an assessment. Repeated erasure preserves the original native
35    /// downcast target rather than retaining nested erased-result envelopes.
36    pub fn new<T: Evaluation + 'static>(native: T) -> Self {
37        if TypeId::of::<T>() == TypeId::of::<Self>() {
38            let native: Box<dyn Any> = Box::new(native);
39            return match native.downcast::<Self>() {
40                Ok(native) => *native,
41                Err(_) => unreachable!("matching erased result type"),
42            };
43        }
44        Self {
45            inner: Box::new(native),
46        }
47    }
48    /// Borrow the original concrete assessment, including any explicitly
49    /// requested native diagnostic data. Returns None for a different type.
50    pub fn native<T: 'static>(&self) -> Option<&T> {
51        self.inner.as_any().downcast_ref()
52    }
53}
54impl Evaluation for ErasedEvaluation {
55    fn visit_scores<'a>(&'a self, visitor: &mut dyn FnMut(Score<'a>)) {
56        crate::eval::EvaluationAccess::visit_scores(&*self.inner, visitor);
57    }
58    fn visit_maps<'a>(&'a self, visitor: &mut dyn FnMut(MapView<'a>)) {
59        crate::eval::EvaluationAccess::visit_maps(&*self.inner, visitor);
60    }
61    fn scores(&self) -> impl Iterator<Item = Score<'_>> {
62        self.inner.scores()
63    }
64    fn maps(&self) -> impl Iterator<Item = MapView<'_>> {
65        self.inner.maps()
66    }
67}
68
69/// A heterogeneous metric object with a common structured result. The lifetime
70/// permits a scorer to borrow configuration; only its owned result must be
71/// static for native downcasting. Use [`crate::score`] for checked evaluation.
72///
73/// ```
74/// use zenpsy_api::{DynMetric, ErasedEvaluation, EvalOpts, MetricResult, score};
75/// use zenpsy_api::zenpixels::PixelView;
76/// fn run_all(metrics: &mut [Box<DynMetric<'_>>], r: &PixelView<'_>, d: &PixelView<'_>)
77///     -> MetricResult<Vec<ErasedEvaluation>>
78/// {
79///     metrics.iter_mut().map(|m| score(m, r, d, EvalOpts::new())).collect()
80/// }
81/// ```
82pub type DynMetric<'a> = dyn Metric<Output = ErasedEvaluation> + 'a;
83
84/// Stackable wrapper normalizing only the result type. It forwards identity,
85/// actual pixel views and operation controls. Typed callers keep their native
86/// result by omitting this wrapper. No Send/Sync bounds are added.
87pub struct Erased<M>(M);
88impl<M> Erased<M> {
89    /// Wrap a typed metric or native prepared reference.
90    pub const fn new(inner: M) -> Self {
91        Self(inner)
92    }
93}
94impl<M: Metric> Metric for Erased<M>
95where
96    M::Output: 'static,
97{
98    type Output = ErasedEvaluation;
99    fn id(&self) -> MetricId {
100        self.0.id()
101    }
102    fn evaluate(
103        &mut self,
104        r: &PixelView<'_>,
105        d: &PixelView<'_>,
106        opts: EvalOpts<'_>,
107    ) -> MetricResult<Self::Output> {
108        self.0.evaluate(r, d, opts).map(ErasedEvaluation::new)
109    }
110}
111impl<P: WarmReference> WarmReference for Erased<P>
112where
113    P::Output: 'static,
114{
115    type Output = ErasedEvaluation;
116    fn evaluate(&mut self, d: &PixelView<'_>, opts: EvalOpts<'_>) -> MetricResult<Self::Output> {
117        self.0.evaluate(d, opts).map(ErasedEvaluation::new)
118    }
119}
120impl<M: PrepareReference> PrepareReference for Erased<M>
121where
122    M::Output: 'static,
123{
124    type Prepared<'a>
125        = Erased<M::Prepared<'a>>
126    where
127        Self: 'a;
128    fn warm_reference(
129        &mut self,
130        r: &PixelView<'_>,
131        opts: EvalOpts<'_>,
132    ) -> MetricResult<Self::Prepared<'_>> {
133        self.0.warm_reference(r, opts).map(Erased::new)
134    }
135}
136
137/// Object-safe optional preparation. Only metrics with native prepared work
138/// implement this extension; a cold metric is not given a replay fallback.
139pub trait DynPrepareReference: Metric<Output = ErasedEvaluation> {
140    /// Prepare checked reference work. Returned objects retain dimensions and
141    /// use fresh candidate controls, without retaining the preparation pulse.
142    fn prepare(
143        &mut self,
144        reference: &PixelView<'_>,
145        opts: EvalOpts<'_>,
146    ) -> MetricResult<Box<dyn WarmReference<Output = ErasedEvaluation> + '_>>;
147}
148struct Checked<P>(PreparedReference<P>);
149impl<P: WarmReference> WarmReference for Checked<P> {
150    type Output = P::Output;
151    fn evaluate(&mut self, d: &PixelView<'_>, opts: EvalOpts<'_>) -> MetricResult<Self::Output> {
152        self.0.score(d, opts)
153    }
154}
155impl<M: PrepareReference> DynPrepareReference for Erased<M>
156where
157    M::Output: 'static,
158{
159    fn prepare(
160        &mut self,
161        r: &PixelView<'_>,
162        opts: EvalOpts<'_>,
163    ) -> MetricResult<Box<dyn WarmReference<Output = ErasedEvaluation> + '_>> {
164        crate::prepare_reference(self, r, opts)
165            .map(|p| Box::new(Checked(p)) as Box<dyn WarmReference<Output = ErasedEvaluation> + '_>)
166    }
167}
168
169// Forwarding lets boxes participate in generic wrapper stacks without adding
170// observation phases, copying pixels or reconstructing native assessments.
171impl<M: Metric + ?Sized> Metric for Box<M> {
172    type Output = M::Output;
173    fn id(&self) -> MetricId {
174        (**self).id()
175    }
176    fn evaluate(
177        &mut self,
178        r: &PixelView<'_>,
179        d: &PixelView<'_>,
180        opts: EvalOpts<'_>,
181    ) -> MetricResult<Self::Output> {
182        (**self).evaluate(r, d, opts)
183    }
184}
185impl<P: WarmReference + ?Sized> WarmReference for Box<P> {
186    type Output = P::Output;
187    fn evaluate(&mut self, d: &PixelView<'_>, opts: EvalOpts<'_>) -> MetricResult<Self::Output> {
188        (**self).evaluate(d, opts)
189    }
190}
191impl<M: PrepareReference + ?Sized> PrepareReference for Box<M> {
192    type Prepared<'a>
193        = M::Prepared<'a>
194    where
195        Self: 'a;
196    fn warm_reference(
197        &mut self,
198        r: &PixelView<'_>,
199        opts: EvalOpts<'_>,
200    ) -> MetricResult<Self::Prepared<'_>> {
201        (**self).warm_reference(r, opts)
202    }
203}
204
205/// A heterogeneous one-image metric object. Scorer configuration may be borrowed;
206/// the erased owned native assessment must be static for downcasting.
207pub type DynNoReferenceMetric<'a> = dyn NoReferenceMetric<Output = ErasedEvaluation> + 'a;
208impl<M: NoReferenceMetric> NoReferenceMetric for Erased<M>
209where
210    M::Output: 'static,
211{
212    type Output = ErasedEvaluation;
213    fn id(&self) -> MetricId {
214        self.0.id()
215    }
216    fn evaluate_image(
217        &mut self,
218        image: &PixelView<'_>,
219        opts: EvalOpts<'_>,
220    ) -> MetricResult<Self::Output> {
221        self.0
222            .evaluate_image(image, opts)
223            .map(ErasedEvaluation::new)
224    }
225}
226impl<M: NoReferenceMetric + ?Sized> NoReferenceMetric for Box<M> {
227    type Output = M::Output;
228    fn id(&self) -> MetricId {
229        (**self).id()
230    }
231    fn evaluate_image(
232        &mut self,
233        image: &PixelView<'_>,
234        opts: EvalOpts<'_>,
235    ) -> MetricResult<Self::Output> {
236        (**self).evaluate_image(image, opts)
237    }
238}
239
240impl<M: crate::PlanarMetric> crate::PlanarMetric for Erased<M>
241where
242    M::Output: 'static,
243{
244    fn evaluate_planar(
245        &mut self,
246        r: &zenpixels::PlanarView<'_>,
247        d: &zenpixels::PlanarView<'_>,
248        opts: EvalOpts<'_>,
249    ) -> MetricResult<Self::Output> {
250        self.0
251            .evaluate_planar(r, d, opts)
252            .map(ErasedEvaluation::new)
253    }
254}
255impl<P: crate::PlanarWarmReference> crate::PlanarWarmReference for Erased<P>
256where
257    P::Output: 'static,
258{
259    type Output = ErasedEvaluation;
260    fn evaluate_planar(
261        &mut self,
262        d: &zenpixels::PlanarView<'_>,
263        opts: EvalOpts<'_>,
264    ) -> MetricResult<Self::Output> {
265        self.0.evaluate_planar(d, opts).map(ErasedEvaluation::new)
266    }
267    fn with_evaluation(
268        &mut self,
269        d: &zenpixels::PlanarView<'_>,
270        opts: EvalOpts<'_>,
271        consumer: &mut dyn FnMut(crate::EvaluationRef<'_>),
272    ) -> MetricResult<()> {
273        self.0.with_evaluation(d, opts, consumer)
274    }
275}
276impl<M: crate::PreparePlanarReference> crate::PreparePlanarReference for Erased<M>
277where
278    M::Output: 'static,
279{
280    type PlanarPrepared = Erased<M::PlanarPrepared>;
281    fn warm_planar_reference(
282        &mut self,
283        r: &zenpixels::PlanarView<'_>,
284        opts: EvalOpts<'_>,
285    ) -> MetricResult<Self::PlanarPrepared> {
286        self.0.warm_planar_reference(r, opts).map(Erased::new)
287    }
288}
289impl<M: crate::PlanarMetric + ?Sized> crate::PlanarMetric for Box<M> {
290    fn evaluate_planar(
291        &mut self,
292        r: &zenpixels::PlanarView<'_>,
293        d: &zenpixels::PlanarView<'_>,
294        opts: EvalOpts<'_>,
295    ) -> MetricResult<Self::Output> {
296        (**self).evaluate_planar(r, d, opts)
297    }
298}
299impl<P: crate::PlanarWarmReference + ?Sized> crate::PlanarWarmReference for Box<P> {
300    type Output = P::Output;
301    fn evaluate_planar(
302        &mut self,
303        d: &zenpixels::PlanarView<'_>,
304        opts: EvalOpts<'_>,
305    ) -> MetricResult<Self::Output> {
306        (**self).evaluate_planar(d, opts)
307    }
308    fn with_evaluation(
309        &mut self,
310        d: &zenpixels::PlanarView<'_>,
311        opts: EvalOpts<'_>,
312        consumer: &mut dyn FnMut(crate::EvaluationRef<'_>),
313    ) -> MetricResult<()> {
314        (**self).with_evaluation(d, opts, consumer)
315    }
316}
317impl<M: crate::PreparePlanarReference + ?Sized> crate::PreparePlanarReference for Box<M> {
318    type PlanarPrepared = M::PlanarPrepared;
319    fn warm_planar_reference(
320        &mut self,
321        r: &zenpixels::PlanarView<'_>,
322        opts: EvalOpts<'_>,
323    ) -> MetricResult<Self::PlanarPrepared> {
324        (**self).warm_planar_reference(r, opts)
325    }
326}
327
328/// Object-safe owned planar preparation for heterogeneous metric collections.
329/// The returned object retains checked geometry and interpretation. Native
330/// prepared state can still lend its map without boxing an assessment.
331pub trait DynPreparePlanarReference: crate::PlanarMetric<Output = ErasedEvaluation> {
332    /// Prepare actual owned native work, with fresh per-candidate controls.
333    fn prepare_planar(
334        &mut self,
335        reference: &zenpixels::PlanarView<'_>,
336        opts: EvalOpts<'_>,
337    ) -> MetricResult<Box<dyn crate::PlanarWarmReference<Output = ErasedEvaluation> + '_>>;
338}
339impl<M: crate::PreparePlanarReference> DynPreparePlanarReference for Erased<M>
340where
341    M::Output: 'static,
342{
343    fn prepare_planar(
344        &mut self,
345        reference: &zenpixels::PlanarView<'_>,
346        opts: EvalOpts<'_>,
347    ) -> MetricResult<Box<dyn crate::PlanarWarmReference<Output = ErasedEvaluation> + '_>> {
348        crate::prepare_planar_reference(self, reference, opts)
349            .map(|p| Box::new(p) as Box<dyn crate::PlanarWarmReference<Output = ErasedEvaluation>>)
350    }
351}