Skip to main content

printobserver_server/
judgements.rs

1//! The records of what the server judged of a print's camera frames.
2//!
3//! Every judgement of a print's first-layer alignment and of its camera's view
4//! is written into the print's history, each naming by its SHA-256 the stored
5//! frame it was made on ([`printobserver_core::ImageRef::sha256`]), so a
6//! reader can open the very frame behind any verdict. Two further kinds are
7//! change notices rather than judgements: the correction a pass put in force
8//! while the landmarks had moved ([`CameraViewRefitPayload`]), and each change
9//! in which image a print's checks are shown, with its reason
10//! ([`CheckImageChangedPayload`]).
11//!
12//! This crate alone writes these kinds, so it declares them, as it declares the
13//! startup reconciliation.
14
15use printobserver_panels::{ViewCorrection, ViewJudgement, ViewOutcome};
16use printobserver_supervisor_api::{ImageFallback, ImageKind};
17use printobserver_types::EventPayload;
18use printobserver_types::contract::Sample;
19use printobserver_types::schemars::JsonSchema;
20use printobserver_types::serde::{Deserialize, Deserializer, Serialize};
21
22/// The version of the `camera_view_judged` record this server writes.
23///
24/// Version 1 carried the frame, its outcome, its reason and the correction in
25/// force, and stated no version: a record with none is a version-1 record.
26/// Version 2 added `landmarks` and `residual_px`, what the judgement measured
27/// on its own frame, so a reader can tell a record that measured nothing it
28/// could write from one written before there was anywhere to write it.
29pub const CAMERA_VIEW_JUDGED_SCHEMA_VERSION: u32 = 2;
30
31/// The version a `camera_view_judged` record stating none is at.
32const fn camera_view_judged_first_version() -> u32 {
33    1
34}
35
36/// A `camera_view_judged` record's version, refusing one this server does not
37/// know: a later one is written by a later release, whose fields this reading
38/// would silently lose.
39fn known_camera_view_judged_version<'de, D>(deserializer: D) -> Result<u32, D::Error>
40where
41    D: Deserializer<'de>,
42{
43    let version = u32::deserialize(deserializer)?;
44    if (1..=CAMERA_VIEW_JUDGED_SCHEMA_VERSION).contains(&version) {
45        Ok(version)
46    } else {
47        Err(printobserver_types::serde::de::Error::custom(format!(
48            "schema_version is {version}, and this program reads camera_view_judged versions 1 to {CAMERA_VIEW_JUDGED_SCHEMA_VERSION}"
49        )))
50    }
51}
52
53/// What one judgement of a print's first layer came to.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
56#[schemars(crate = "printobserver_types::schemars")]
57pub enum AlignmentJudgedVerdict {
58    /// The first layer is clearly found, and its offset is the print's
59    /// correction from now on.
60    Passed,
61    /// The frame could not tell; a later check's frame is judged again.
62    Inconclusive,
63    /// The camera's frames cannot be judged against the calibration, which
64    /// holds for the rest of the print.
65    Failed,
66}
67
68/// One judgement of a print's first-layer alignment, on one frame.
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
70#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
71#[schemars(crate = "printobserver_types::schemars")]
72pub struct FirstLayerAlignmentJudgedPayload {
73    /// What it came to.
74    pub verdict: AlignmentJudgedVerdict,
75    /// How far the printed first layer was found from its uncorrected
76    /// projection, in calibration pixels; null when it was not searched for.
77    pub offset_px: Option<f64>,
78    /// The correction the pass put in force, `[dx, dy]` pixels; null unless it
79    /// passed.
80    pub correction_px: Option<[f64; 2]>,
81    /// The peak smoothed contrast the layer was found at, in grey levels; null
82    /// when it was not searched for.
83    pub match_strength: Option<f64>,
84    /// `clearly_found` for a pass, `covered` or `not_clearly_found` for an
85    /// inconclusive judgement, and the failure's own sentence for a failure.
86    pub reason: String,
87    /// The stored frame it was judged on.
88    pub frame_sha256: String,
89    /// The correction in force when the frame was judged; null before the
90    /// print's first pass.
91    pub view_correction: Option<ViewCorrection>,
92}
93
94impl EventPayload for FirstLayerAlignmentJudgedPayload {
95    const KIND: &'static str = "first_layer_alignment_judged";
96}
97
98/// One judgement of a print's camera view, on one frame: one for every
99/// judgement, whatever it found and whether or not it repeats the last.
100///
101/// `view_correction` is what the frame was judged *against*, so it repeats
102/// from check to check for as long as one correction stays in force;
103/// `landmarks` and `residual_px` are what was measured on *this* frame.
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
105#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
106#[schemars(crate = "printobserver_types::schemars")]
107pub struct CameraViewJudgedPayload {
108    /// The version of this record: the schema's maximum for every record
109    /// this server writes, and 1 for a record stating none, which was written
110    /// before `landmarks` and `residual_px` existed.
111    #[serde(
112        default = "camera_view_judged_first_version",
113        deserialize_with = "known_camera_view_judged_version"
114    )]
115    #[schemars(range(min = 1, max = CAMERA_VIEW_JUDGED_SCHEMA_VERSION))]
116    pub schema_version: u32,
117    /// The stored frame it was judged on.
118    pub frame_sha256: String,
119    /// What it found.
120    pub outcome: ViewOutcome,
121    /// The correction in force when the frame was judged; null when none was.
122    /// Its landmarks are the reference this frame was compared against, found
123    /// on the frame the correction was taken on rather than on this one.
124    pub view_correction: Option<ViewCorrection>,
125    /// Why the frame may not be drawn on: for the three refusals, and for a
126    /// refit view, whose camera has moved since its calibration; null for an
127    /// unshifted one.
128    pub reason: Option<String>,
129    /// Every landmark of the calibration as this frame showed it, in the
130    /// calibration's order; absent when the frame could not be searched, as
131    /// one of another size or stream cannot.
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub landmarks: Vec<JudgedLandmark>,
134    /// The RMS distance, over this frame's visible landmarks, between where
135    /// it showed them and where the judgement expected them: the correction
136    /// in force's reference, over the landmarks it names, or each landmark's
137    /// calibrated place when none is in force. Absent when no landmark it
138    /// compared was visible.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub residual_px: Option<f64>,
141}
142
143/// One landmark of the calibration as one judged frame showed it.
144#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
145#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
146#[schemars(crate = "printobserver_types::schemars")]
147pub struct JudgedLandmark {
148    /// The calibration's name for it.
149    pub name: String,
150    /// How far from its calibrated place this frame showed it, `[dx, dy]`
151    /// pixels.
152    pub offset_px: [f64; 2],
153    /// The correlation it was found at.
154    pub score: f64,
155    /// Whether it was found at all, rather than hidden by the head, the
156    /// gantry or a part; a hidden landmark's offset is where its search
157    /// scored best, and counts for nothing.
158    pub visible: bool,
159    /// How far it lies from where the correction in force's reference had it,
160    /// in pixels; absent when no correction is in force or its reference does
161    /// not name this landmark.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub from_reference_px: Option<f64>,
164}
165
166impl CameraViewJudgedPayload {
167    /// The record of one view judgement of the frame `frame_sha256`: what it
168    /// found, and every landmark the judgement measured on that frame,
169    /// against the correction in force.
170    #[must_use]
171    pub fn of(
172        frame_sha256: &str,
173        view: &ViewJudgement,
174        view_correction: Option<ViewCorrection>,
175        reason: Option<String>,
176    ) -> Self {
177        let landmarks: Vec<JudgedLandmark> = view
178            .landmarks
179            .iter()
180            .map(|found| JudgedLandmark {
181                name: found.name.clone(),
182                offset_px: found.located.offset_px,
183                score: f64::from(found.located.score),
184                visible: found.visible(),
185                from_reference_px: view_correction.as_ref().and_then(|correction| {
186                    correction
187                        .landmarks
188                        .iter()
189                        .find(|reference| reference.name == found.name)
190                        .map(|reference| {
191                            (found.located.offset_px[0] - reference.offset_px[0])
192                                .hypot(found.located.offset_px[1] - reference.offset_px[1])
193                        })
194                }),
195            })
196            .collect();
197        let compared: Vec<f64> = landmarks
198            .iter()
199            .filter(|landmark| landmark.visible)
200            .filter_map(|landmark| match view_correction {
201                Some(_) => landmark.from_reference_px,
202                None => Some(landmark.offset_px[0].hypot(landmark.offset_px[1])),
203            })
204            .collect();
205        let residual_px = (!compared.is_empty()).then(|| {
206            let count = f64::from(u32::try_from(compared.len()).unwrap_or(u32::MAX));
207            (compared
208                .iter()
209                .map(|distance| distance * distance)
210                .sum::<f64>()
211                / count)
212                .sqrt()
213        });
214        Self {
215            schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
216            frame_sha256: frame_sha256.to_owned(),
217            outcome: view.outcome,
218            view_correction,
219            reason,
220            landmarks,
221            residual_px,
222        }
223    }
224}
225
226impl EventPayload for CameraViewJudgedPayload {
227    const KIND: &'static str = "camera_view_judged";
228}
229
230/// A first-layer pass put a correction in force while the landmarks had moved
231/// from the calibration: the print's first, or one taken again after the
232/// camera moved again.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
234#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
235#[schemars(crate = "printobserver_types::schemars")]
236pub struct CameraViewRefitPayload {
237    /// The stored frame the correction was taken on.
238    pub frame_sha256: String,
239    /// The correction now in force.
240    pub view_correction: ViewCorrection,
241}
242
243impl EventPayload for CameraViewRefitPayload {
244    const KIND: &'static str = "camera_view_refit";
245}
246
247/// The image a print's checks are shown changed: its first check's image, and
248/// every check whose image kind or fallback code differs from the last one
249/// recorded.
250#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
251#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
252#[schemars(crate = "printobserver_types::schemars")]
253pub struct CheckImageChangedPayload {
254    /// Which image the check was shown.
255    pub kind: ImageKind,
256    /// Why it was the whole frame; null for the three-panel image.
257    pub fallback: Option<ImageFallback>,
258    /// The stored frame the check's image was made of.
259    pub frame_sha256: String,
260}
261
262impl EventPayload for CheckImageChangedPayload {
263    const KIND: &'static str = "check_image_changed";
264}
265
266/// A frame's SHA-256, as samples name one.
267const SAMPLE_SHA256: &str = "9f2c4d1e8b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f1e";
268
269/// The correction samples carry.
270fn sample_correction() -> ViewCorrection {
271    ViewCorrection::translation(
272        [14.0, 4.0],
273        vec![
274            printobserver_panels::ReferenceLandmark {
275                name: "frame-screws-right-front".to_owned(),
276                offset_px: [59.1, 0.7],
277                score: 0.83,
278            },
279            printobserver_panels::ReferenceLandmark {
280                name: "frame-label-right".to_owned(),
281                offset_px: [79.6, 0.2],
282                score: 0.84,
283            },
284        ],
285    )
286}
287
288impl Sample for FirstLayerAlignmentJudgedPayload {
289    fn sample_full() -> Self {
290        Self {
291            verdict: AlignmentJudgedVerdict::Passed,
292            offset_px: Some(14.6),
293            correction_px: Some([14.0, 4.0]),
294            match_strength: Some(57.6),
295            reason: "clearly_found".to_owned(),
296            frame_sha256: SAMPLE_SHA256.to_owned(),
297            view_correction: Some(sample_correction()),
298        }
299    }
300
301    fn sample_minimal() -> Self {
302        Self {
303            verdict: AlignmentJudgedVerdict::Inconclusive,
304            offset_px: None,
305            correction_px: None,
306            match_strength: None,
307            reason: "not_clearly_found".to_owned(),
308            frame_sha256: SAMPLE_SHA256.to_owned(),
309            view_correction: None,
310        }
311    }
312
313    fn sample_alternates() -> Vec<Self> {
314        vec![Self {
315            verdict: AlignmentJudgedVerdict::Failed,
316            reason: "the camera is not the stream the calibration was fitted on".to_owned(),
317            ..Self::sample_minimal()
318        }]
319    }
320}
321
322impl Sample for CameraViewJudgedPayload {
323    fn sample_full() -> Self {
324        Self {
325            schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
326            frame_sha256: SAMPLE_SHA256.to_owned(),
327            outcome: ViewOutcome::ViewRefitRejected,
328            view_correction: Some(sample_correction()),
329            reason: Some(
330                "the camera has moved again since this print's first-layer correction was taken: frame-label-right is 10.2 px from where that correction's frame had it"
331                    .to_owned(),
332            ),
333            landmarks: vec![
334                JudgedLandmark {
335                    name: "frame-screws-right-front".to_owned(),
336                    offset_px: [68.4, 1.1],
337                    score: 0.81,
338                    visible: true,
339                    from_reference_px: Some(9.3),
340                },
341                JudgedLandmark {
342                    name: "frame-label-right".to_owned(),
343                    offset_px: [89.8, 0.4],
344                    score: 0.79,
345                    visible: true,
346                    from_reference_px: Some(10.2),
347                },
348                JudgedLandmark {
349                    name: "chassis-corner-top-right".to_owned(),
350                    offset_px: [12.0, -40.5],
351                    score: 0.31,
352                    visible: false,
353                    from_reference_px: None,
354                },
355            ],
356            residual_px: Some(9.76),
357        }
358    }
359
360    fn sample_minimal() -> Self {
361        Self {
362            schema_version: CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
363            frame_sha256: SAMPLE_SHA256.to_owned(),
364            outcome: ViewOutcome::Unshifted,
365            view_correction: None,
366            reason: None,
367            landmarks: Vec::new(),
368            residual_px: None,
369        }
370    }
371
372    fn sample_alternates() -> Vec<Self> {
373        [
374            ViewOutcome::Refit,
375            ViewOutcome::LandmarksNotFound,
376            ViewOutcome::FrameMismatch,
377        ]
378        .into_iter()
379        .map(|outcome| Self {
380            outcome,
381            ..Self::sample_minimal()
382        })
383        .collect()
384    }
385}
386
387impl Sample for CameraViewRefitPayload {
388    fn sample_full() -> Self {
389        Self {
390            frame_sha256: SAMPLE_SHA256.to_owned(),
391            view_correction: sample_correction(),
392        }
393    }
394}
395
396impl Sample for CheckImageChangedPayload {
397    fn sample_full() -> Self {
398        Self {
399            kind: ImageKind::WholeFrame,
400            fallback: Some(ImageFallback::sample_full()),
401            frame_sha256: SAMPLE_SHA256.to_owned(),
402        }
403    }
404
405    fn sample_minimal() -> Self {
406        Self {
407            kind: ImageKind::ThreePanel,
408            fallback: None,
409            frame_sha256: SAMPLE_SHA256.to_owned(),
410        }
411    }
412}