1use crate::{ErrorKind, Evaluation, MetricError, MetricId, MetricResult, fail};
3use alloc::vec::Vec;
4use core::fmt;
5use how_far::{Complete, NoPulse, Pulse, Stop};
6use whereat::ResultAtExt as _;
7use zenpixels::PixelView;
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum MapRequest<'a> {
13 None,
15 Native,
17 Named(&'a str),
19}
20
21#[non_exhaustive]
23#[derive(Clone, Copy)]
24pub struct EvalOpts<'a> {
25 pulse: &'a dyn Pulse,
27 max_pixels: Option<u64>,
29 maps: MapRequest<'a>,
30}
31impl fmt::Debug for EvalOpts<'_> {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.debug_struct("EvalOpts")
34 .field("maps", &self.maps)
35 .field("max_pixels", &self.max_pixels)
36 .finish_non_exhaustive()
37 }
38}
39impl Default for EvalOpts<'_> {
40 fn default() -> Self {
41 Self::new()
42 }
43}
44impl<'a> EvalOpts<'a> {
45 pub const fn new() -> EvalOpts<'static> {
47 EvalOpts {
48 pulse: &NoPulse,
49 max_pixels: None,
50 maps: MapRequest::None,
51 }
52 }
53 pub const fn with_native_map(mut self) -> Self {
56 self.maps = MapRequest::Native;
57 self
58 }
59 pub(crate) const fn without_diagnostics(mut self) -> Self {
60 self.maps = MapRequest::None;
61 self
62 }
63 pub fn with_map<'b>(self, key: &'b str) -> EvalOpts<'b>
66 where
67 'a: 'b,
68 {
69 EvalOpts {
70 pulse: self.pulse,
71 max_pixels: self.max_pixels,
72 maps: MapRequest::Named(key),
73 }
74 }
75 pub const fn map_request(&self) -> MapRequest<'a> {
77 self.maps
78 }
79 pub const fn diagnostics(&self) -> bool {
81 !matches!(self.maps, MapRequest::None)
82 }
83 pub fn with_pulse<'b>(self, pulse: &'b dyn Pulse) -> EvalOpts<'b>
85 where
86 'a: 'b,
87 {
88 EvalOpts {
89 pulse,
90 max_pixels: self.max_pixels,
91 maps: self.maps,
92 }
93 }
94 pub const fn with_max_pixels(mut self, limit: u64) -> Self {
96 self.max_pixels = Some(limit);
97 self
98 }
99 pub const fn pulse(&self) -> &'a dyn Pulse {
101 self.pulse
102 }
103 pub const fn max_pixels(&self) -> Option<u64> {
105 self.max_pixels
106 }
107 pub fn stop(&self) -> &'a dyn Stop {
109 self.pulse
110 }
111 #[track_caller]
113 pub fn checkpoint(&self) -> MetricResult<()> {
114 self.pulse
115 .check()
116 .map_err(|r| whereat::at(MetricError::stopped(r)))
117 }
118}
119pub trait Metric {
122 type Output: Evaluation;
124 fn id(&self) -> MetricId;
126 fn evaluate(
129 &mut self,
130 reference: &PixelView<'_>,
131 candidate: &PixelView<'_>,
132 opts: EvalOpts<'_>,
133 ) -> MetricResult<Self::Output>;
134}
135pub trait PrepareReference: Metric {
137 type Prepared<'a>: WarmReference<Output = Self::Output>
140 where
141 Self: 'a;
142 fn warm_reference(
144 &mut self,
145 reference: &PixelView<'_>,
146 opts: EvalOpts<'_>,
147 ) -> MetricResult<Self::Prepared<'_>>;
148}
149pub trait WarmReference {
152 type Output: Evaluation;
154 fn evaluate(
156 &mut self,
157 candidate: &PixelView<'_>,
158 opts: EvalOpts<'_>,
159 ) -> MetricResult<Self::Output>;
160}
161pub struct PreparedReference<P> {
163 size: (u32, u32),
164 inner: P,
165}
166impl<P: WarmReference> PreparedReference<P> {
167 #[track_caller]
169 pub fn score(&mut self, image: &PixelView<'_>, opts: EvalOpts<'_>) -> MetricResult<P::Output> {
170 operation(opts, "score prepared image", |opts| {
171 admit(image, opts)?;
172 if (image.width(), image.height()) != self.size {
173 return fail(MetricError::new(ErrorKind::DimensionMismatch));
174 }
175 let result = self.inner.evaluate(image, opts).at()?;
176 validate(&result)?;
177 validate_maps(&result, image.width(), image.height(), opts)?;
178 opts.checkpoint()?;
179 Ok(result)
180 })
181 }
182}
183#[track_caller]
184fn admit(image: &PixelView<'_>, opts: EvalOpts<'_>) -> MetricResult<()> {
185 admit_geometry(image.width(), image.height(), opts)
186}
187#[track_caller]
190pub(crate) fn admit_geometry(width: u32, height: u32, opts: EvalOpts<'_>) -> MetricResult<()> {
191 opts.checkpoint()?;
192 if matches!(opts.maps, MapRequest::Named("")) {
193 return fail(MetricError::new(ErrorKind::InvalidConfig).with_message("empty map request"));
194 }
195 if width == 0 || height == 0 {
196 return fail(MetricError::new(ErrorKind::InvalidInput));
197 }
198 if opts
199 .max_pixels
200 .is_some_and(|limit| u64::from(width) * u64::from(height) > limit)
201 {
202 return fail(MetricError::new(ErrorKind::Resource));
203 }
204 Ok(())
205}
206#[track_caller]
207fn validate(result: &impl Evaluation) -> MetricResult<()> {
208 validate_scores(crate::EvaluationRef::new(result))
209}
210
211#[track_caller]
214fn insert_name<'a>(names: &mut Vec<&'a str>, key: &'a str) -> MetricResult<()> {
215 if key.is_empty() || names.contains(&key) {
216 return fail(
217 MetricError::new(ErrorKind::Internal).with_message("empty or duplicate output key"),
218 );
219 }
220 names
221 .try_reserve(1)
222 .map_err(|e| whereat::at(MetricError::from_detail(ErrorKind::Resource, e)))?;
223 names.push(key);
224 Ok(())
225}
226#[track_caller]
227pub(crate) fn validate_scores(result: crate::EvaluationRef<'_>) -> MetricResult<()> {
228 let mut names = Vec::new();
229 let mut status = Ok(());
230 let mut count = 0;
231 result.visit_scores(|score| {
232 if status.is_err() {
233 return;
234 }
235 count += 1;
236 if !score.value.is_finite()
237 && !(score.spec.positive_infinity() && score.value == f64::INFINITY)
238 {
239 status =
240 fail(MetricError::new(ErrorKind::Internal).with_message("invalid native score"));
241 } else {
242 status = insert_name(&mut names, score.spec.key());
243 }
244 });
245 status?;
246 if count == 0 {
247 return fail(MetricError::new(ErrorKind::Internal).with_message("empty native score set"));
248 }
249 Ok(())
250}
251#[track_caller]
252pub(crate) fn operation<T>(
253 opts: EvalOpts<'_>,
254 label: &'static str,
255 work: impl FnOnce(EvalOpts<'_>) -> MetricResult<T>,
256) -> MetricResult<T> {
257 let mut stages = how_far::Stages::new(
258 opts.pulse,
259 &[how_far::PhaseSpec::new(label, 1, how_far::Total::Unknown)],
260 );
261 let result = stages.run_classified(crate::is_stopped, |pulse| work(opts.with_pulse(pulse)));
262 stages.complete_classified(result, crate::is_stopped).at()
263}
264#[track_caller]
267pub fn score<M: Metric + ?Sized>(
268 metric: &mut M,
269 reference: &PixelView<'_>,
270 candidate: &PixelView<'_>,
271 opts: EvalOpts<'_>,
272) -> MetricResult<M::Output> {
273 operation(opts, "score image pair", |opts| {
274 admit(reference, opts)?;
275 admit(candidate, opts)?;
276 if (reference.width(), reference.height()) != (candidate.width(), candidate.height()) {
277 return fail(MetricError::new(ErrorKind::DimensionMismatch));
278 }
279 let result = metric.evaluate(reference, candidate, opts).at()?;
280 validate(&result)?;
281 validate_maps(&result, candidate.width(), candidate.height(), opts)?;
282 opts.checkpoint()?;
283 Ok(result)
284 })
285}
286#[track_caller]
288pub fn prepare_reference<'a, M: PrepareReference + ?Sized>(
289 metric: &'a mut M,
290 reference: &PixelView<'_>,
291 opts: EvalOpts<'_>,
292) -> MetricResult<PreparedReference<M::Prepared<'a>>> {
293 operation(opts, "prepare image reference", |opts| {
294 admit(reference, opts)?;
295 let inner = metric.warm_reference(reference, opts).at()?;
296 opts.checkpoint()?;
297 Ok(PreparedReference {
298 size: (reference.width(), reference.height()),
299 inner,
300 })
301 })
302}
303
304#[track_caller]
306pub fn score_image<M: crate::NoReferenceMetric + ?Sized>(
307 metric: &mut M,
308 image: &PixelView<'_>,
309 opts: EvalOpts<'_>,
310) -> MetricResult<M::Output> {
311 operation(opts, "score one image", |opts| {
312 admit(image, opts)?;
313 let result = metric.evaluate_image(image, opts).at()?;
314 validate(&result)?;
315 validate_maps(&result, image.width(), image.height(), opts)?;
316 opts.checkpoint()?;
317 Ok(result)
318 })
319}
320#[track_caller]
321fn validate_maps(
322 result: &impl Evaluation,
323 width: u32,
324 height: u32,
325 opts: EvalOpts<'_>,
326) -> MetricResult<()> {
327 validate_map_views(crate::EvaluationRef::new(result), width, height, opts)
328}
329#[track_caller]
330pub(crate) fn validate_map_views(
331 result: crate::EvaluationRef<'_>,
332 width: u32,
333 height: u32,
334 opts: EvalOpts<'_>,
335) -> MetricResult<()> {
336 if !opts.diagnostics() {
337 return Ok(());
338 }
339 let mut names = Vec::new();
340 let mut found = false;
341 let mut status = Ok(());
342 result.visit_maps(|map| {
343 if status.is_err() {
344 return;
345 }
346 if map.values.width() == 0
347 || map.values.height() == 0
348 || map.grid.input_width() != width
349 || map.grid.input_height() != height
350 {
351 status =
352 fail(MetricError::new(ErrorKind::Internal).with_message("invalid native map view"));
353 return;
354 }
355 found |= matches!(opts.maps, MapRequest::Named(key) if key == map.spec.key());
356 status = insert_name(&mut names, map.spec.key());
357 });
358 status?;
359 if matches!(opts.maps, MapRequest::Named(_)) && !found {
360 return fail(
361 MetricError::new(ErrorKind::NoMap)
362 .with_message("requested common map was not returned"),
363 );
364 }
365 Ok(())
366}