1use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::{Error, Result};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
12#[serde(rename_all = "lowercase")]
13pub enum AnnotationType {
14 Point,
16 Box,
18 Polygon,
20 Line,
22 Arrow,
24 Text,
26 Vline,
28 Hline,
30 Vband,
32 Hband,
34 Well,
36}
37
38impl AnnotationType {
39 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
61#[serde(deny_unknown_fields)]
62pub struct Annotation {
63 #[serde(rename = "type")]
65 pub kind: AnnotationType,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub x: Option<f64>,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub y: Option<f64>,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub x2: Option<f64>,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub y2: Option<f64>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub width: Option<f64>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub height: Option<f64>,
84 #[serde(default, skip_serializing_if = "Vec::is_empty")]
86 pub points: Vec<[f64; 2]>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub label: Option<String>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub color: Option<String>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub channel: Option<u32>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub well: Option<String>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub facet: Option<String>,
105}
106
107impl Annotation {
108 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 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 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 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 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 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 let old = serde_json::from_value::<Annotation>(serde_json::json!({"x": [1, 2]}));
261 assert!(old.is_err());
262 }
263}