Skip to main content

openreadout_core/
annotation.rs

1//! The caller's marks on a picture: one shape for previews (`annotations`) and plots
2//! (`annotate`). Coordinates are those the picture shows: full-resolution pixels on images (as
3//! on the rulers), axis units on plots (as on the tick labels), wells on plates.
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::{Error, Result};
9
10/// What an annotation draws.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
12#[serde(rename_all = "lowercase")]
13pub enum AnnotationType {
14    /// a dot at x, y (with its label beside it)
15    Point,
16    /// a rectangle: corner x, y and width, height
17    Box,
18    /// a closed outline through points
19    Polygon,
20    /// an open line through points
21    Line,
22    /// an arrow from x, y (where the label goes) to x2, y2
23    Arrow,
24    /// the label alone, at x, y
25    Text,
26    /// a vertical line at x
27    Vline,
28    /// a horizontal line at y
29    Hline,
30    /// a vertical band from x to x2
31    Vband,
32    /// a horizontal band from y to y2
33    Hband,
34    /// a ring around a plate well (well; previews of plates only)
35    Well,
36}
37
38impl AnnotationType {
39    /// The name as written in a request.
40    pub fn name(self) -> &'static str {
41        match self {
42            AnnotationType::Point => "point",
43            AnnotationType::Box => "box",
44            AnnotationType::Polygon => "polygon",
45            AnnotationType::Line => "line",
46            AnnotationType::Arrow => "arrow",
47            AnnotationType::Text => "text",
48            AnnotationType::Vline => "vline",
49            AnnotationType::Hline => "hline",
50            AnnotationType::Vband => "vband",
51            AnnotationType::Hband => "hband",
52            AnnotationType::Well => "well",
53        }
54    }
55}
56
57/// One annotation, in the coordinates the picture shows: full-resolution pixels on images (as
58/// on the rulers), axis units on plots (as on the tick labels), and on plate curve grids the
59/// time and value axes every card shares.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
61#[serde(deny_unknown_fields)]
62pub struct Annotation {
63    /// What to draw.
64    #[serde(rename = "type")]
65    pub kind: AnnotationType,
66    /// point, text: position; box: corner; arrow: tail; vline, vband: x (vband from x to x2).
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub x: Option<f64>,
69    /// point, text: position; box: corner; arrow: tail; hline, hband: y (hband from y to y2).
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub y: Option<f64>,
72    /// arrow: head; vband: other edge.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub x2: Option<f64>,
75    /// arrow: head; hband: other edge.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub y2: Option<f64>,
78    /// box: width.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub width: Option<f64>,
81    /// box: height.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub height: Option<f64>,
84    /// polygon, line: the vertices, `[[x, y], ...]`.
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub points: Vec<[f64; 2]>,
87    /// Text drawn with the mark (the text itself for type text).
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub label: Option<String>,
90    /// `accent` (default, warm red), `ink`, `muted`, `white`, another colour name or `#RRGGBB`.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub color: Option<String>,
93    /// Trace previews with several panels: the channel whose panel it goes in (default: the
94    /// first panel).
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub channel: Option<u32>,
97    /// Plate previews: the well (e.g. `B3`) for type well, or the one card a mark goes in on a
98    /// curve grid (default: every card).
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub well: Option<String>,
101    /// Plots with small multiples: the one small plot it goes in, by its title (e.g. `B3` or
102    /// `sweep 6`; default: every one).
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub facet: Option<String>,
105}
106
107impl Annotation {
108    /// An annotation of `kind` with nothing set.
109    pub fn new(kind: AnnotationType) -> Annotation {
110        Annotation {
111            kind,
112            x: None,
113            y: None,
114            x2: None,
115            y2: None,
116            width: None,
117            height: None,
118            points: Vec::new(),
119            label: None,
120            color: None,
121            channel: None,
122            well: None,
123            facet: None,
124        }
125    }
126
127    /// A point with a label.
128    pub fn point(x: f64, y: f64, label: &str) -> Annotation {
129        Annotation {
130            x: Some(x),
131            y: Some(y),
132            label: Some(label.to_string()),
133            ..Annotation::new(AnnotationType::Point)
134        }
135    }
136
137    /// A label alone at (x, y).
138    pub fn text(x: f64, y: f64, label: &str) -> Annotation {
139        Annotation {
140            x: Some(x),
141            y: Some(y),
142            label: Some(label.to_string()),
143            ..Annotation::new(AnnotationType::Text)
144        }
145    }
146
147    /// A rectangle with its corner at (x, y).
148    pub fn rect(x: f64, y: f64, width: f64, height: f64) -> Annotation {
149        Annotation {
150            x: Some(x),
151            y: Some(y),
152            width: Some(width),
153            height: Some(height),
154            ..Annotation::new(AnnotationType::Box)
155        }
156    }
157
158    /// A straight line from (x0, y0) to (x1, y1).
159    pub fn segment(x0: f64, y0: f64, x1: f64, y1: f64) -> Annotation {
160        Annotation {
161            points: vec![[x0, y0], [x1, y1]],
162            ..Annotation::new(AnnotationType::Line)
163        }
164    }
165
166    /// Check that the annotation has what its type needs (a usage error naming what is
167    /// missing).
168    pub fn check(&self) -> Result<()> {
169        let k = self.kind.name();
170        let need = |v: Option<f64>, what: &str| match v {
171            Some(v) if v.is_finite() => Ok(()),
172            _ => Err(Error::Usage(format!(
173                "annotation type {k} needs a finite {what}"
174            ))),
175        };
176        match self.kind {
177            AnnotationType::Point => {
178                need(self.x, "x")?;
179                need(self.y, "y")?;
180            }
181            AnnotationType::Text => {
182                need(self.x, "x")?;
183                need(self.y, "y")?;
184                if self.label.as_deref().is_none_or(|l| l.trim().is_empty()) {
185                    return Err(Error::Usage("annotation type text needs a label".into()));
186                }
187            }
188            AnnotationType::Box => {
189                need(self.x, "x")?;
190                need(self.y, "y")?;
191                need(self.width, "width")?;
192                need(self.height, "height")?;
193            }
194            AnnotationType::Arrow => {
195                need(self.x, "x")?;
196                need(self.y, "y")?;
197                need(self.x2, "x2")?;
198                need(self.y2, "y2")?;
199            }
200            AnnotationType::Polygon | AnnotationType::Line => {
201                let min = if self.kind == AnnotationType::Polygon {
202                    3
203                } else {
204                    2
205                };
206                if self.points.len() < min || self.points.iter().flatten().any(|v| !v.is_finite()) {
207                    return Err(Error::Usage(format!(
208                        "annotation type {k} needs at least {min} finite points [[x, y], ...]"
209                    )));
210                }
211            }
212            AnnotationType::Vline => need(self.x, "x")?,
213            AnnotationType::Hline => need(self.y, "y")?,
214            AnnotationType::Vband => {
215                need(self.x, "x")?;
216                need(self.x2, "x2")?;
217            }
218            AnnotationType::Hband => {
219                need(self.y, "y")?;
220                need(self.y2, "y2")?;
221            }
222            AnnotationType::Well => {
223                let w = self.well.as_deref().unwrap_or("");
224                if crate::plate::parse_well(w).is_none() {
225                    return Err(Error::Usage(format!(
226                        "annotation type well needs a well such as \"B3\" (got '{w}')"
227                    )));
228                }
229            }
230        }
231        if let Some(w) = self.well.as_deref()
232            && crate::plate::parse_well(w).is_none()
233        {
234            return Err(Error::Usage(format!(
235                "annotation well '{w}' is not a well name such as B3"
236            )));
237        }
238        Ok(())
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn one_shape_parses_and_checks() {
248        let a: Annotation = serde_json::from_value(serde_json::json!(
249            {"type": "vband", "x": 206.5, "x2": 240, "label": "two sequences"}
250        ))
251        .unwrap();
252        assert_eq!(
253            (a.kind, a.x, a.x2),
254            (AnnotationType::Vband, Some(206.5), Some(240.0))
255        );
256        a.check().unwrap();
257        let e = Annotation::new(AnnotationType::Vband).check().unwrap_err();
258        assert!(e.to_string().contains("needs a finite x"), "{e}");
259        // the old plot spelling is refused with the field it does not know
260        let old = serde_json::from_value::<Annotation>(serde_json::json!({"x": [1, 2]}));
261        assert!(old.is_err());
262    }
263}