Skip to main content

openreadout_preview/
options.rs

1//! A preview request as JSON, with the names `openreadout_preview` uses. The Python, R and
2//! WebAssembly bindings take their preview options in this form, so the three agree with the
3//! MCP tool on every name and default.
4
5use openreadout_core::{Error, Region, Result};
6use schemars::JsonSchema;
7use serde::{Deserialize, Deserializer};
8
9use crate::{Annotation, Axes, Axis, Contrast, Lut, Marks, PreviewRequest};
10
11/// One string or a list of them.
12fn one_or_many<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
13    #[derive(Deserialize)]
14    #[serde(untagged)]
15    enum OneOrMany {
16        One(String),
17        Many(Vec<String>),
18    }
19    Ok(match Option::<OneOrMany>::deserialize(d)? {
20        None => Vec::new(),
21        Some(OneOrMany::One(s)) => vec![s],
22        Some(OneOrMany::Many(v)) => v,
23    })
24}
25
26/// Preview options by name. Every field is optional; [`PreviewOptions::request`] fills in the
27/// defaults. The MCP tool `openreadout_preview` takes these fields as its arguments, so their
28/// documentation is also what an agent reads.
29#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
30#[serde(deny_unknown_fields)]
31#[non_exhaustive]
32pub struct PreviewOptions {
33    /// Image index (default 0).
34    pub image: Option<u32>,
35    /// Plane selection such as `c=1`, `z=4`, `t=0` or combined `c=0,1,z=2`. Default: c=0, the
36    /// middle z, t=0. Several channels imply a composite.
37    #[serde(default, deserialize_with = "one_or_many")]
38    #[schemars(with = "Vec<String>")]
39    pub select: Vec<String>,
40    /// Maximum-intensity projection, over the selected range if any.
41    pub mip: Option<Axis>,
42    /// Volumes: the plane to show. `axial`, `coronal`, `sagittal` (radiological orientation),
43    /// `orthogonal` (all three, crossing at the middle or the selected z), `xz`, `yz`, or
44    /// `native` (as stored). Default: medical images in their acquisition plane, others native.
45    /// With a view, `z` and `mip: z` count slices of that view.
46    pub view: Option<crate::View>,
47    /// Sum projection, over the selected range if any: a movie's frames added up (e.g. sum t,
48    /// select t=0-39).
49    pub sum: Option<Axis>,
50    /// Images: a power-spectrum (FFT) inset in the top-right corner: Thon rings of a cryo-EM
51    /// micrograph, the spots of a lattice.
52    #[serde(default)]
53    pub fft: bool,
54    /// Blend all (or the selected) channels additively in their colours.
55    #[serde(default)]
56    pub composite: bool,
57    /// Pyramid level to read (default: the level nearest max_size, or the level at which
58    /// `region` renders at about max_size).
59    pub level: Option<u32>,
60    /// Zoom: only this rectangle, `{x, y, width, height}` in full-resolution pixels (or in the
61    /// pixels of `level` when a level is given). Whole-slide images: look at the overview
62    /// first, then at regions of it.
63    pub region: Option<Region>,
64    /// Longest side in pixels, rulers included (MCP: default 768, at most 2048).
65    pub max_size: Option<u32>,
66    /// Image previews: what frames the picture.
67    pub axes: Option<Axes>,
68    /// Image previews with axes scale-bar: a title above the picture.
69    pub title: Option<String>,
70    /// Image previews with axes scale-bar: a caption under the picture (what it shows, the
71    /// stain, the sample).
72    pub caption: Option<String>,
73    /// `auto` (default; the file's display window when it has one, `log:90,99.95` on diffraction
74    /// images), `min-max`, `percentile:LO,HI` (e.g. `percentile:1,99`), `log` (`log:50,99.9`)
75    /// or `log:LO,HI`, `raw`, or a display window `window:CENTER,WIDTH` (`window:40,400`),
76    /// `window:file`, or a CT preset `window:soft-tissue`, `brain`, `subdural`, `stroke`, `bone`,
77    /// `lung`, `mediastinum`, `liver`.
78    pub contrast: Option<String>,
79    /// Colour lookup. Default: gray for one channel (inverted on diffraction images), channel
80    /// colours for composites.
81    pub lut: Option<Lut>,
82    /// Trace preview: trace index (see openreadout_info traces[]).
83    pub trace: Option<u32>,
84    /// Trace preview: sweep index.
85    pub sweep: Option<u32>,
86    /// Trace preview: channel indices (default: the first 8).
87    #[serde(default)]
88    pub channels: Vec<u32>,
89    /// Trace preview: only this window of the x axis, `[a, b]` in its units (bp of a sized electropherogram, base positions of a Sanger read, minutes, ppm, …).
90    pub x_range: Option<[f64; 2]>,
91    /// Spectrum preview: run index.
92    pub run: Option<u32>,
93    /// Spectrum preview: zero-based spectrum index.
94    pub spectrum: Option<u64>,
95    /// Spectrum preview: instrument scan number instead of an index.
96    pub scan: Option<u64>,
97    /// Spectrum preview: the instrument's centroid list instead of the profile.
98    #[serde(default)]
99    pub centroid: bool,
100    /// Plate or flow-cytometry preview: table index.
101    pub table: Option<u32>,
102    /// Table columns: a plate's value column, or the x and y parameters of a flow-cytometry
103    /// density plot (one gives a histogram; default FSC-A, SSC-A).
104    #[serde(default, deserialize_with = "one_or_many")]
105    #[schemars(with = "Vec<String>")]
106    pub columns: Vec<String>,
107    /// Marks from the data. Default auto: the prominent peaks of spectra and chromatograms are
108    /// labelled; diffraction images get resolution rings.
109    pub marks: Option<Marks>,
110    /// Images: how objects are found for `marks: objects` (as `openreadout_stats` objects).
111    pub objects: Option<openreadout_core::measure::ObjectsRequest>,
112    /// Gels and blots: how lanes are found for `marks: lanes` (as `openreadout_stats` lanes).
113    pub lanes: Option<openreadout_core::measure::LanesRequest>,
114    /// Your own marks, drawn on top and reported back with their pixel positions. Coordinates
115    /// as the picture shows them: full-resolution pixels on images (the ruler numbers), axis
116    /// units on plots, wells on plates.
117    #[serde(default)]
118    pub annotations: Vec<Annotation>,
119    /// Draw in the dark theme.
120    #[serde(default)]
121    pub dark: bool,
122}
123
124impl PreviewOptions {
125    /// Parse options from JSON text; empty text gives the defaults.
126    pub fn from_json(text: &str) -> Result<PreviewOptions> {
127        if text.trim().is_empty() {
128            return Ok(PreviewOptions::default());
129        }
130        serde_json::from_str(text).map_err(|e| Error::Usage(format!("preview options: {e}")))
131    }
132
133    /// The request these options describe. `default_size` is the `max_size` when none is given
134    /// and `default_axes` the frame of image previews.
135    pub fn request(&self, default_size: u32, default_axes: Axes) -> Result<PreviewRequest> {
136        let mut r = PreviewRequest {
137            image: self.image,
138            select: self.select.clone(),
139            mip: self.mip,
140            view: self.view,
141            sum: self.sum,
142            fft: self.fft,
143            composite: self.composite,
144            level: self.level,
145            region: self.region,
146            max_size: self.max_size.unwrap_or(default_size),
147            contrast: match self.contrast.as_deref() {
148                None => Contrast::Auto,
149                Some(s) => s.parse()?,
150            },
151            lut: self.lut,
152            trace: self.trace,
153            sweep: self.sweep,
154            channels: self.channels.clone(),
155            x_range: self.x_range,
156            run: self.run,
157            spectrum: self.spectrum,
158            scan: self.scan,
159            centroid: self.centroid,
160            table: self.table,
161            columns: self.columns.clone(),
162            marks: self.marks.unwrap_or_default(),
163            objects: self.objects.clone(),
164            lanes: self.lanes.clone(),
165            annotations: self.annotations.clone(),
166            dark: self.dark,
167            title: self.title.clone(),
168            caption: self.caption.clone(),
169            ..PreviewRequest::default()
170        };
171        // a title or caption asks for the figure frame, which draws them
172        let text = self.title.is_some() || self.caption.is_some();
173        let axes = self
174            .axes
175            .unwrap_or(if text { Axes::ScaleBar } else { default_axes });
176        axes.apply(&mut r);
177        Ok(r)
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn names_and_defaults() {
187        let o = PreviewOptions::from_json(
188            r#"{"select": "c=1", "columns": ["FSC-A", "SSC-A"], "axes": "grid", "dark": true,
189                "annotations": [{"type": "point", "x": 10, "y": 20, "label": "a"}],
190                "contrast": "percentile:1,99", "marks": "spikes"}"#,
191        )
192        .unwrap();
193        let r = o.request(512, Axes::None).unwrap();
194        assert_eq!(r.select, vec!["c=1"]);
195        assert_eq!(r.columns.len(), 2);
196        assert!(r.axes && r.grid && r.dark);
197        assert_eq!(r.max_size, 512);
198        assert_eq!(r.contrast, Contrast::Percentile(1.0, 99.0));
199        assert_eq!(r.marks, Marks::Spikes);
200        assert_eq!(r.annotations.len(), 1);
201        let bare = PreviewOptions::from_json("").unwrap();
202        assert!(!bare.request(512, Axes::None).unwrap().axes);
203    }
204
205    #[test]
206    fn a_title_asks_for_the_figure_frame() {
207        let o = PreviewOptions::from_json(r#"{"title": "Cerebellum"}"#).unwrap();
208        let r = o.request(512, Axes::Rulers).unwrap();
209        assert!(r.axes && r.figure && !r.grid);
210        assert_eq!(r.title.as_deref(), Some("Cerebellum"));
211        let o = PreviewOptions::from_json(r#"{"axes": "scale-bar"}"#).unwrap();
212        assert!(o.request(512, Axes::Rulers).unwrap().figure);
213        let o = PreviewOptions::from_json(r#"{"title": "x", "axes": "rulers"}"#).unwrap();
214        assert!(!o.request(512, Axes::None).unwrap().figure);
215        assert!(
216            !PreviewOptions::default()
217                .request(512, Axes::Rulers)
218                .unwrap()
219                .figure
220        );
221    }
222
223    #[test]
224    fn unknown_keys_are_refused() {
225        let e = PreviewOptions::from_json(r#"{"colour": 1}"#).unwrap_err();
226        assert!(e.to_string().contains("colour"), "{e}");
227        assert!(
228            PreviewOptions::from_json(r#"{"contrast": "loud"}"#)
229                .unwrap()
230                .request(512, Axes::Rulers)
231                .is_err()
232        );
233    }
234}