1#![forbid(unsafe_code)]
62#![warn(missing_docs)]
63#![allow(clippy::many_single_char_names)]
65
66mod annotate;
67pub mod color;
68mod diffraction;
69pub mod electrochem;
70mod electrophoresis;
71mod events;
72mod fft_inset;
73mod figure_frame;
74mod image;
75mod kinetic;
76mod lanes;
77mod marks;
78mod nmr;
79mod objects;
80mod options;
81mod overlay;
82mod plate;
83mod rulers;
84mod samples;
85mod sequencing;
86mod spectrum;
87mod tic;
88mod trace;
89mod volume;
90
91use std::path::{Path, PathBuf};
92use std::str::FromStr;
93
94use openreadout_core::model::FileInfo;
95use openreadout_core::reader::Dataset;
96use openreadout_core::{Error, Result};
97use schemars::JsonSchema;
98use serde::{Deserialize, Serialize};
99
100pub use annotate::{Annotation, AnnotationType, DrawnAnnotation};
101pub use electrophoresis::series_index_of;
102pub use openreadout_figure::{Figure, Raster};
103pub use options::PreviewOptions;
104pub use plate::{PlateGrid, plate_grid};
105pub use volume::View;
106
107pub const MAX_PREVIEW_SIZE: u32 = 8192;
109pub const DEFAULT_PREVIEW_SIZE: u32 = 1024;
111pub const DEFAULT_JPEG_QUALITY: u8 = 90;
113pub const DEFAULT_THUMBNAIL_SIZE: u32 = 384;
115pub const DEFAULT_THUMBNAIL_READ_BYTES: u64 = 32 << 20;
117pub const MIN_TRACE_SAMPLES_OVER_SPECTRUM: u64 = 100;
120
121#[derive(Debug, Clone, Copy, PartialEq, Default)]
123#[non_exhaustive]
124pub enum Contrast {
125 #[default]
127 Auto,
128 MinMax,
130 Percentile(f64, f64),
132 Raw,
134 Window(f64, f64),
137 StoredWindow(usize),
139 Log(f64, f64),
143}
144
145pub const WINDOW_PRESETS: &[(&str, f64, f64)] = &[
147 ("soft-tissue", 40.0, 400.0),
148 ("brain", 40.0, 80.0),
149 ("subdural", 75.0, 215.0),
150 ("stroke", 40.0, 40.0),
151 ("bone", 400.0, 1800.0),
152 ("lung", -600.0, 1500.0),
153 ("mediastinum", 50.0, 350.0),
154 ("liver", 60.0, 150.0),
155];
156
157pub const LOG_PERCENTILES: (f64, f64) = (50.0, 99.9);
159
160impl FromStr for Contrast {
161 type Err = Error;
162 fn from_str(s: &str) -> Result<Self> {
163 let s = s.trim().to_ascii_lowercase();
164 match s.as_str() {
165 "auto" => Ok(Contrast::Auto),
166 "min-max" | "minmax" => Ok(Contrast::MinMax),
167 "raw" => Ok(Contrast::Raw),
168 "log" => Ok(Contrast::Log(LOG_PERCENTILES.0, LOG_PERCENTILES.1)),
169 _ if s.starts_with("window") => {
170 let bad = || {
171 let names: Vec<&str> = WINDOW_PRESETS.iter().map(|p| p.0).collect();
172 Error::Usage(format!(
173 "bad contrast '{s}': use window:CENTER,WIDTH (e.g. window:40,400), window:file (the file's own window; window:file:2 for the third), or a preset: window:{}",
174 names.join(", window:")
175 ))
176 };
177 let spec = s.strip_prefix("window:").ok_or_else(bad)?.trim();
178 if let Some(rest) = spec.strip_prefix("file") {
179 let n = match rest.strip_prefix(':') {
180 Some(n) => n.trim().parse().map_err(|_| bad())?,
181 None if rest.is_empty() => 0,
182 None => return Err(bad()),
183 };
184 return Ok(Contrast::StoredWindow(n));
185 }
186 if let Some((_, c, w)) = WINDOW_PRESETS
187 .iter()
188 .find(|p| p.0 == spec.replace('_', "-"))
189 {
190 return Ok(Contrast::Window(*c, *w));
191 }
192 let (c, w) = spec.split_once(',').ok_or_else(bad)?;
193 let (c, w): (f64, f64) = (
194 c.trim().parse().map_err(|_| bad())?,
195 w.trim().parse().map_err(|_| bad())?,
196 );
197 if !c.is_finite() || !w.is_finite() || w <= 0.0 {
198 return Err(bad());
199 }
200 Ok(Contrast::Window(c, w))
201 }
202 _ => {
203 let bad = || {
204 Error::Usage(format!(
205 "bad contrast '{s}': use auto, min-max, raw, percentile:LO,HI (e.g. percentile:1,99), log or log:LO,HI, or window:CENTER,WIDTH (window:brain, window:bone, ...)"
206 ))
207 };
208 let (log, spec) = match s.strip_prefix("log:") {
209 Some(rest) => (true, rest),
210 None => (false, s.strip_prefix("percentile:").ok_or_else(bad)?),
211 };
212 let (a, b) = spec.split_once(',').ok_or_else(bad)?;
213 let (a, b): (f64, f64) = (
214 a.trim().parse().map_err(|_| bad())?,
215 b.trim().parse().map_err(|_| bad())?,
216 );
217 if !(0.0..=100.0).contains(&a) || !(0.0..=100.0).contains(&b) || a >= b {
218 return Err(bad());
219 }
220 Ok(if log {
221 Contrast::Log(a, b)
222 } else {
223 Contrast::Percentile(a, b)
224 })
225 }
226 }
227 }
228}
229
230impl std::fmt::Display for Contrast {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 match self {
233 Contrast::Auto => f.write_str("auto"),
234 Contrast::MinMax => f.write_str("min-max"),
235 Contrast::Percentile(a, b) => write!(f, "percentile:{a},{b}"),
236 Contrast::Raw => f.write_str("raw"),
237 Contrast::Window(c, w) => write!(f, "window:{c},{w}"),
238 Contrast::StoredWindow(n) => write!(f, "window:file:{n}"),
239 Contrast::Log(a, b) => write!(f, "log:{a},{b}"),
240 }
241 }
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
246#[serde(rename_all = "kebab-case")]
247#[non_exhaustive]
248pub enum Lut {
249 #[serde(alias = "grey")]
251 Gray,
252 #[serde(alias = "channel-colour", alias = "color")]
254 ChannelColor,
255 Inverted,
257}
258
259impl FromStr for Lut {
260 type Err = Error;
261 fn from_str(s: &str) -> Result<Self> {
262 match s.trim().to_ascii_lowercase().as_str() {
263 "gray" | "grey" => Ok(Lut::Gray),
264 "channel-color" | "channel-colour" | "color" => Ok(Lut::ChannelColor),
265 "inverted" => Ok(Lut::Inverted),
266 other => Err(Error::Usage(format!(
267 "bad lut '{other}': use gray, inverted or channel-color"
268 ))),
269 }
270 }
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
275#[serde(rename_all = "lowercase")]
276#[non_exhaustive]
277pub enum Axis {
278 Z,
280 T,
282}
283
284#[derive(
286 Debug,
287 Clone,
288 Copy,
289 PartialEq,
290 Eq,
291 Default,
292 serde::Deserialize,
293 serde::Serialize,
294 schemars::JsonSchema,
295)]
296#[serde(rename_all = "kebab-case")]
297#[non_exhaustive]
298pub enum Axes {
299 #[default]
301 Rulers,
302 Grid,
304 ScaleBar,
306 None,
308}
309
310impl Axes {
311 pub fn apply(self, req: &mut PreviewRequest) {
313 req.axes = self != Axes::None;
314 req.grid = self == Axes::Grid;
315 req.figure = self == Axes::ScaleBar;
316 }
317}
318
319impl FromStr for Axes {
320 type Err = Error;
321 fn from_str(s: &str) -> Result<Self> {
322 match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
323 "rulers" => Ok(Axes::Rulers),
324 "grid" => Ok(Axes::Grid),
325 "scale-bar" | "scalebar" => Ok(Axes::ScaleBar),
326 "none" => Ok(Axes::None),
327 other => Err(Error::Usage(format!(
328 "bad axes '{other}': use rulers, grid, scale-bar or none"
329 ))),
330 }
331 }
332}
333
334impl FromStr for Axis {
335 type Err = Error;
336 fn from_str(s: &str) -> Result<Self> {
337 match s.trim().to_ascii_lowercase().as_str() {
338 "z" => Ok(Axis::Z),
339 "t" => Ok(Axis::T),
340 other => Err(Error::Usage(format!(
341 "bad projection axis '{other}': use z or t"
342 ))),
343 }
344 }
345}
346
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, schemars::JsonSchema)]
349#[serde(rename_all = "lowercase")]
350#[non_exhaustive]
351pub enum Encoding {
352 #[default]
354 Png,
355 #[serde(alias = "jpg")]
357 Jpeg,
358 Svg,
360}
361
362impl Encoding {
363 pub fn as_str(self) -> &'static str {
365 match self {
366 Encoding::Png => "png",
367 Encoding::Jpeg => "jpeg",
368 Encoding::Svg => "svg",
369 }
370 }
371 pub fn mime(self) -> &'static str {
373 match self {
374 Encoding::Png => "image/png",
375 Encoding::Jpeg => "image/jpeg",
376 Encoding::Svg => "image/svg+xml",
377 }
378 }
379 pub fn extension(self) -> &'static str {
381 match self {
382 Encoding::Png => "png",
383 Encoding::Jpeg => "jpg",
384 Encoding::Svg => "svg",
385 }
386 }
387 pub fn from_path(p: &Path) -> Self {
389 match p
390 .extension()
391 .and_then(|e| e.to_str())
392 .map(str::to_ascii_lowercase)
393 .as_deref()
394 {
395 Some("jpg" | "jpeg") => Encoding::Jpeg,
396 Some("svg") => Encoding::Svg,
397 _ => Encoding::Png,
398 }
399 }
400}
401
402impl FromStr for Encoding {
403 type Err = Error;
404 fn from_str(s: &str) -> Result<Self> {
405 match s.trim().to_ascii_lowercase().as_str() {
406 "png" => Ok(Encoding::Png),
407 "jpeg" | "jpg" => Ok(Encoding::Jpeg),
408 "svg" => Ok(Encoding::Svg),
409 other => Err(Error::Usage(format!(
410 "bad preview format '{other}': use png, jpeg or svg"
411 ))),
412 }
413 }
414}
415
416#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, schemars::JsonSchema)]
418#[serde(rename_all = "lowercase")]
419#[non_exhaustive]
420pub enum Marks {
421 #[default]
423 Auto,
424 Peaks,
426 Spikes,
428 Objects,
430 Lanes,
432 Rings,
435 None,
437}
438
439impl FromStr for Marks {
440 type Err = Error;
441 fn from_str(s: &str) -> Result<Self> {
442 match s.trim().to_ascii_lowercase().as_str() {
443 "auto" => Ok(Marks::Auto),
444 "peaks" => Ok(Marks::Peaks),
445 "spikes" => Ok(Marks::Spikes),
446 "objects" => Ok(Marks::Objects),
447 "lanes" => Ok(Marks::Lanes),
448 "rings" => Ok(Marks::Rings),
449 "none" => Ok(Marks::None),
450 other => Err(Error::Usage(format!(
451 "bad marks '{other}': use auto, peaks, spikes, objects, lanes, rings or none"
452 ))),
453 }
454 }
455}
456
457#[derive(Debug, Clone)]
459#[non_exhaustive]
460pub struct PreviewRequest {
461 pub image: Option<u32>,
463 pub select: Vec<String>,
465 pub mip: Option<Axis>,
467 pub view: Option<View>,
470 pub sum: Option<Axis>,
472 pub fft: bool,
474 pub composite: bool,
476 pub level: Option<u32>,
478 pub region: Option<openreadout_core::Region>,
482 pub max_size: u32,
484 pub contrast: Contrast,
486 pub lut: Option<Lut>,
488 pub trace: Option<u32>,
490 pub sweep: Option<u32>,
492 pub channels: Vec<u32>,
494 pub x_range: Option<[f64; 2]>,
496 pub run: Option<u32>,
498 pub spectrum: Option<u64>,
500 pub scan: Option<u64>,
502 pub centroid: bool,
504 pub table: Option<u32>,
506 pub columns: Vec<String>,
510 pub marks: Marks,
512 pub objects: Option<openreadout_core::measure::ObjectsRequest>,
514 pub lanes: Option<openreadout_core::measure::LanesRequest>,
516 pub annotations: Vec<Annotation>,
518 pub dark: bool,
520 pub axes: bool,
524 pub grid: bool,
527 pub figure: bool,
530 pub title: Option<String>,
532 pub caption: Option<String>,
534 pub max_read_bytes: Option<u64>,
537}
538
539impl Default for PreviewRequest {
540 fn default() -> Self {
541 PreviewRequest {
542 image: None,
543 select: Vec::new(),
544 mip: None,
545 view: None,
546 sum: None,
547 fft: false,
548 composite: false,
549 level: None,
550 region: None,
551 max_size: DEFAULT_PREVIEW_SIZE,
552 contrast: Contrast::Auto,
553 lut: None,
554 trace: None,
555 sweep: None,
556 channels: Vec::new(),
557 x_range: None,
558 run: None,
559 spectrum: None,
560 scan: None,
561 centroid: false,
562 table: None,
563 columns: Vec::new(),
564 marks: Marks::Auto,
565 objects: None,
566 lanes: None,
567 annotations: Vec::new(),
568 dark: false,
569 axes: true,
570 grid: false,
571 figure: false,
572 title: None,
573 caption: None,
574 max_read_bytes: None,
575 }
576 }
577}
578
579fn render_image(
581 ds: &mut dyn Dataset,
582 info: &FileInfo,
583 req: &PreviewRequest,
584 out: &mut PreviewOutput,
585) -> Result<(Figure, Frame)> {
586 let image = req.image.unwrap_or(0);
587 let Some(im) = info.images.iter().find(|i| i.index == image) else {
588 return image::render(ds, info, req, out);
589 };
590 let Some(view) = volume::effective(info, im, req.view) else {
591 return image::render(ds, info, req, out);
592 };
593 let sel = openreadout_core::select::Selection::parse(&split_select(&req.select))?;
594 let mut req = req.clone();
595 let select_z = sel.z.first().copied();
596 if view == View::Orthogonal {
597 let join = |a: &str, v: &[u32]| {
599 (!v.is_empty()).then(|| {
600 format!(
601 "{a}={}",
602 v.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
603 )
604 })
605 };
606 req.select = [join("c", &sel.c), join("t", &sel.t)]
607 .into_iter()
608 .flatten()
609 .collect();
610 if req.mip.is_some() {
611 return Err(Error::Usage(
612 "an orthogonal view shows three slices; project with view axial, coronal or sagittal and mip z".into(),
613 ));
614 }
615 if req.axes && !req.figure {
616 req.figure = true;
618 req.grid = false;
619 out.notes
620 .push("orthogonal views are framed with a scale bar, not rulers".into());
621 }
622 }
623 let (mut vds, vim, marks, notes) = volume::ViewDataset::new(ds, info, image, view, select_z)?;
624 out.notes.extend(notes);
625 let slices = vim.size_z;
626 let mut vinfo = info.clone();
627 if let Some(slot) = vinfo.images.iter_mut().find(|i| i.index == image) {
628 *slot = vim;
629 }
630 let (mut figure, frame) = image::render(&mut vds, &vinfo, &req, out)?;
631 if !marks.is_empty() {
633 let theme = theme(&req);
634 annotate::draw(&mut figure, &frame, &marks, &theme, &mut Vec::new())?;
635 }
636 let drawn = (figure, frame);
637 if let Some(p) = out.image.as_mut() {
638 p.view = Some(
639 match vds.view() {
640 View::Axial => "axial",
641 View::Coronal => "coronal",
642 View::Sagittal => "sagittal",
643 View::Orthogonal => "orthogonal",
644 View::Xz => "xz",
645 View::Yz => "yz",
646 View::Native => "native",
647 }
648 .into(),
649 );
650 p.crosshair = vds.point();
651 p.view_slices = Some(slices);
652 }
653 if req.view.is_none() {
654 out.notes.push(format!(
655 "shown as a radiological {} view (view: native shows the stored orientation)",
656 out.image
657 .as_ref()
658 .and_then(|p| p.view.clone())
659 .unwrap_or_default()
660 ));
661 }
662 let _ = vds.ortho_step();
663 Ok(drawn)
664}
665
666pub(crate) fn theme(req: &PreviewRequest) -> openreadout_figure::Theme {
668 let t = if req.dark {
669 openreadout_figure::Theme::dark()
670 } else {
671 openreadout_figure::Theme::light()
672 };
673 t.for_size(req.max_size as f32)
674}
675
676#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
678pub struct PreviewChannel {
679 pub index: u32,
681 #[serde(skip_serializing_if = "Option::is_none")]
683 pub name: Option<String>,
684 pub color: String,
686 pub color_source: String,
688 pub display_min: f64,
690 pub display_max: f64,
692}
693
694#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
696pub struct SourcePoint {
697 pub x: f64,
699 pub y: f64,
701}
702
703#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
705pub struct ScaleBar {
706 pub length: f64,
708 pub unit: String,
710 pub length_um: f64,
712 pub pixels: u32,
714}
715
716#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
724pub struct ImagePreview {
725 pub image: u32,
727 pub level: u32,
729 pub source_width: u32,
731 pub source_height: u32,
733 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub region: Option<openreadout_core::Region>,
736 pub downsample: f64,
740 pub c: Vec<u32>,
742 pub z: Vec<u32>,
744 pub t: Vec<u32>,
746 #[serde(skip_serializing_if = "Option::is_none")]
748 pub projection: Option<String>,
749 pub composite: bool,
751 pub rgb: bool,
753 pub contrast: String,
755 pub lut: String,
757 pub channels: Vec<PreviewChannel>,
759 #[serde(default)]
762 pub axes: bool,
763 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
765 pub grid: bool,
766 #[serde(default)]
768 pub plot_area: openreadout_core::Region,
769 #[serde(default)]
771 pub source_origin: SourcePoint,
772 #[serde(default)]
775 pub source_per_pixel: f64,
776 #[serde(default)]
779 pub source_per_pixel_y: f64,
780 #[serde(default)]
783 pub full_res_region: openreadout_core::Region,
784 #[serde(default, skip_serializing_if = "Option::is_none")]
786 pub fft_inset: Option<openreadout_core::Region>,
787 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub scale_bar: Option<ScaleBar>,
790 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub view: Option<String>,
795 #[serde(default, skip_serializing_if = "Option::is_none")]
797 pub crosshair: Option<[u32; 3]>,
798 #[serde(default, skip_serializing_if = "Option::is_none")]
800 pub view_slices: Option<u32>,
801}
802
803impl ImagePreview {
804 pub fn pixel_mapping(&self) -> String {
807 let n = |v: f64| {
808 let s = format!("{v:.3}");
809 s.trim_end_matches('0').trim_end_matches('.').to_string()
810 };
811 let term = |origin: f64, edge: u32, per: f64, p: &str| {
812 let at = if edge == 0 {
813 p.to_string()
814 } else {
815 format!("({p} − {edge})")
816 };
817 if origin == 0.0 {
818 format!("{at} × {}", n(per))
819 } else {
820 format!("{} + {at} × {}", n(origin), n(per))
821 }
822 };
823 format!(
824 "this picture has no rulers: picture pixel (px, py) is full-res x = {}, y = {}",
825 term(
826 self.source_origin.x,
827 self.plot_area.x,
828 self.source_per_pixel,
829 "px"
830 ),
831 term(
832 self.source_origin.y,
833 self.plot_area.y,
834 self.source_per_pixel_y,
835 "py"
836 ),
837 )
838 }
839
840 fn halve(&mut self) {
842 let (plot, origin, per) = rulers::halve(
843 self.plot_area,
844 self.source_origin,
845 (self.source_per_pixel, self.source_per_pixel_y),
846 );
847 self.plot_area = plot;
848 self.source_origin = origin;
849 (self.source_per_pixel, self.source_per_pixel_y) = per;
850 if let Some(b) = &mut self.scale_bar {
851 b.pixels = b.pixels.div_ceil(2);
852 }
853 }
854}
855
856#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
858pub struct TracePreviewChannel {
859 pub index: u32,
861 pub name: String,
863 #[serde(skip_serializing_if = "Option::is_none")]
865 pub unit: Option<String>,
866 pub color: String,
868 #[serde(skip_serializing_if = "Option::is_none")]
870 pub min: Option<f64>,
871 #[serde(skip_serializing_if = "Option::is_none")]
873 pub max: Option<f64>,
874}
875
876#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
878pub struct XAxis {
879 pub quantity: String,
881 pub unit: String,
883 pub first: f64,
885 pub last: f64,
887}
888
889#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
891pub struct TracePreview {
892 pub trace: u32,
894 pub sweep: u32,
896 pub sample_rate_hz: f64,
898 pub sweep_sample_count: u64,
900 pub sample_count: u64,
902 pub truncated: bool,
904 #[serde(skip_serializing_if = "Option::is_none")]
906 pub x_axis: Option<XAxis>,
907 pub channels: Vec<TracePreviewChannel>,
909}
910
911#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
913pub struct SpectrumPreview {
914 pub run: u32,
916 pub index: u64,
918 pub scan_number: u64,
920 pub ms_level: u32,
922 pub rt_s: Option<f64>,
924 pub style: String,
926 pub point_count: u64,
928 pub x_axis: XAxis,
930 #[serde(skip_serializing_if = "Option::is_none")]
932 pub max_intensity: Option<f64>,
933 #[serde(skip_serializing_if = "Option::is_none")]
935 pub precursor_mz: Option<f64>,
936}
937
938#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
940pub struct ChromatogramPreview {
941 pub run: u32,
943 pub signal: String,
945 pub ms1_scans: u64,
947 pub scans: u64,
949 pub apex_rt_min: f64,
951 pub apex_intensity: f64,
953}
954
955#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
957pub struct PlateGroup {
958 pub name: String,
960 pub color: String,
962 pub wells: u32,
964 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
966 pub blank: bool,
967}
968
969#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
971pub struct PlatePreview {
972 pub table: u32,
974 pub layout: String,
976 pub view: String,
978 pub rows: u32,
980 pub columns: u32,
982 pub wells: u32,
984 pub value: String,
986 #[serde(skip_serializing_if = "Option::is_none")]
989 pub min: Option<f64>,
990 #[serde(skip_serializing_if = "Option::is_none")]
992 pub max: Option<f64>,
993 #[serde(default, skip_serializing_if = "Option::is_none")]
995 pub time: Option<[f64; 2]>,
996 #[serde(default, skip_serializing_if = "Option::is_none")]
998 pub time_unit: Option<String>,
999 #[serde(default, skip_serializing_if = "Option::is_none")]
1001 pub grouped_by: Option<String>,
1002 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1004 pub groups: Vec<PlateGroup>,
1005}
1006
1007#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1009pub struct EventsPreview {
1010 pub table: u32,
1012 pub x: String,
1014 #[serde(default, skip_serializing_if = "Option::is_none")]
1016 pub y: Option<String>,
1017 pub events: u64,
1019 pub total_events: u64,
1021 pub scales: Vec<String>,
1023}
1024
1025#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1029pub struct PlotPanel {
1030 pub plot_area: PxRect,
1032 pub x: [f64; 2],
1034 pub y: [f64; 2],
1036 pub x_scale: String,
1038 pub y_scale: String,
1040 #[serde(default, skip_serializing_if = "Option::is_none")]
1042 pub channel: Option<u32>,
1043 #[serde(default, skip_serializing_if = "Option::is_none")]
1045 pub well: Option<String>,
1046}
1047
1048#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
1050pub struct PxRect {
1051 pub x: f64,
1053 pub y: f64,
1055 pub width: f64,
1057 pub height: f64,
1059}
1060
1061impl From<openreadout_figure::Rect> for PxRect {
1062 fn from(r: openreadout_figure::Rect) -> Self {
1063 let q = |v: f32| (f64::from(v) * 100.0).round() / 100.0;
1064 PxRect {
1065 x: q(r.x),
1066 y: q(r.y),
1067 width: q(r.w),
1068 height: q(r.h),
1069 }
1070 }
1071}
1072
1073#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1075pub struct DataMark {
1076 pub kind: String,
1079 pub x: f64,
1081 pub y: f64,
1083 #[serde(default, skip_serializing_if = "Option::is_none")]
1085 pub label: Option<String>,
1086 #[serde(default, skip_serializing_if = "Option::is_none")]
1088 pub channel: Option<u32>,
1089}
1090
1091#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1093pub struct PreviewOutput {
1094 pub path: String,
1096 pub format: String,
1098 pub kind: String,
1100 #[serde(skip_serializing_if = "Option::is_none")]
1102 pub output: Option<String>,
1103 pub encoding: String,
1105 pub width: u32,
1107 pub height: u32,
1109 pub bytes: u64,
1111 pub xxh3: String,
1113 pub verified: bool,
1115 #[serde(skip_serializing_if = "Option::is_none")]
1117 pub image: Option<ImagePreview>,
1118 #[serde(skip_serializing_if = "Option::is_none")]
1120 pub trace: Option<TracePreview>,
1121 #[serde(skip_serializing_if = "Option::is_none")]
1123 pub spectrum: Option<SpectrumPreview>,
1124 #[serde(default, skip_serializing_if = "Option::is_none")]
1126 pub chromatogram: Option<ChromatogramPreview>,
1127 #[serde(skip_serializing_if = "Option::is_none")]
1129 pub plate: Option<PlatePreview>,
1130 #[serde(skip_serializing_if = "Option::is_none")]
1132 pub events: Option<EventsPreview>,
1133 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1136 pub panels: Vec<PlotPanel>,
1137 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1139 pub marks: Vec<DataMark>,
1140 #[serde(default, skip_serializing_if = "Option::is_none")]
1143 #[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
1144 pub objects: Option<openreadout_core::measure::Objects>,
1145 #[serde(default, skip_serializing_if = "Option::is_none")]
1147 #[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
1148 pub lanes: Option<openreadout_core::measure::Lanes>,
1149 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1151 pub annotations: Vec<DrawnAnnotation>,
1152 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1154 pub notes: Vec<String>,
1155 #[serde(default, skip_serializing_if = "Option::is_none")]
1157 pub hint: Option<String>,
1158 #[serde(default, skip_serializing_if = "Option::is_none")]
1160 pub save: Option<String>,
1161}
1162
1163impl PreviewOutput {
1164 fn halved(&mut self) {
1166 if let Some(im) = &mut self.image {
1167 im.halve();
1168 }
1169 let h = |r: &mut PxRect| {
1170 r.x /= 2.0;
1171 r.y /= 2.0;
1172 r.width /= 2.0;
1173 r.height /= 2.0;
1174 };
1175 for p in &mut self.panels {
1176 h(&mut p.plot_area);
1177 }
1178 for a in &mut self.annotations {
1179 a.halve();
1180 }
1181 }
1182}
1183
1184#[derive(Debug, Clone)]
1186pub(crate) enum Frame {
1187 Image {
1189 plot_area: openreadout_core::Region,
1190 map: rulers::Mapping,
1191 },
1192 Plots {
1195 panels: Vec<FramePanel>,
1196 key: Option<KeySlot>,
1197 taken: Vec<openreadout_figure::Rect>,
1199 },
1200 Wells(Vec<((u32, u32), openreadout_figure::Rect)>),
1202}
1203
1204impl Frame {
1205 pub(crate) fn plots(panels: Vec<FramePanel>) -> Frame {
1207 Frame::Plots {
1208 panels,
1209 key: None,
1210 taken: Vec::new(),
1211 }
1212 }
1213
1214 pub(crate) fn plots_labelled(
1216 panels: Vec<FramePanel>,
1217 taken: &[openreadout_figure::Rect],
1218 ) -> Frame {
1219 Frame::Plots {
1220 panels,
1221 key: None,
1222 taken: taken.to_vec(),
1223 }
1224 }
1225}
1226
1227#[derive(Debug, Clone, Copy, PartialEq)]
1230pub(crate) struct KeySlot {
1231 pub x: f32,
1232 pub y: f32,
1233 pub max_x: f32,
1234}
1235
1236#[derive(Debug, Clone)]
1238pub(crate) struct FramePanel {
1239 pub panel: openreadout_figure::Panel,
1240 pub channel: Option<u32>,
1241 pub well: Option<(u32, u32)>,
1242}
1243
1244impl FramePanel {
1245 pub(crate) fn new(panel: openreadout_figure::Panel) -> Self {
1246 FramePanel {
1247 panel,
1248 channel: None,
1249 well: None,
1250 }
1251 }
1252}
1253
1254#[derive(Debug, Clone)]
1256pub struct Rendered {
1257 pub canvas: Raster,
1259 pub figure: Figure,
1261 pub output: PreviewOutput,
1263}
1264
1265impl Rendered {
1266 pub fn take_pixels(&mut self, big: &Rendered, scale: f32) -> bool {
1271 use openreadout_figure::Item;
1272 fn largest(f: &Figure) -> Option<usize> {
1273 f.items
1274 .iter()
1275 .enumerate()
1276 .filter_map(|(i, it)| match it {
1277 Item::Image { rect, .. } => Some((i, rect.w * rect.h)),
1278 _ => None,
1279 })
1280 .max_by(|a, b| a.1.total_cmp(&b.1))
1281 .map(|x| x.0)
1282 }
1283 let (Some(i), Some(j)) = (largest(&self.figure), largest(&big.figure)) else {
1284 return false;
1285 };
1286 let Item::Image { raster, .. } = &big.figure.items[j] else {
1287 return false;
1288 };
1289 let raster = raster.clone();
1290 let Item::Image {
1291 rect,
1292 raster: mine,
1293 smooth,
1294 } = &mut self.figure.items[i]
1295 else {
1296 return false;
1297 };
1298 let (w, h) = (raster.width as f32, raster.height as f32);
1302 let same_shape = (w / h - rect.w / rect.h).abs() <= 0.02 * rect.w / rect.h;
1303 if !same_shape || w <= mine.width as f32 {
1304 return false;
1305 }
1306 if (w - rect.w * scale).abs() > 1.0 {
1307 *smooth = true;
1308 }
1309 *mine = raster;
1310 true
1311 }
1312}
1313
1314pub fn split_select(args: &[String]) -> Vec<String> {
1317 let mut out: Vec<String> = Vec::new();
1318 for a in args {
1319 let mut cur = String::new();
1320 for part in a.split(',') {
1321 if part.contains('=') && !cur.is_empty() {
1322 out.push(std::mem::take(&mut cur));
1323 }
1324 if !cur.is_empty() {
1325 cur.push(',');
1326 }
1327 cur.push_str(part.trim());
1328 }
1329 if !cur.is_empty() {
1330 out.push(cur);
1331 }
1332 }
1333 out
1334}
1335
1336fn kind(info: &FileInfo, req: &PreviewRequest) -> Result<&'static str> {
1338 if req.table.is_some() || !req.columns.is_empty() {
1339 return Ok(if events::is_events(info, req.table.unwrap_or(0)) {
1340 "events"
1341 } else {
1342 "plate"
1343 });
1344 }
1345 if req.trace.is_some()
1346 || req.sweep.is_some()
1347 || !req.channels.is_empty()
1348 || req.x_range.is_some()
1349 {
1350 return Ok("trace");
1351 }
1352 if req.run.is_some() || req.spectrum.is_some() || req.scan.is_some() || req.centroid {
1353 return Ok("spectrum");
1354 }
1355 let short_traces = info
1358 .traces
1359 .iter()
1360 .all(|t| t.sample_count < MIN_TRACE_SAMPLES_OVER_SPECTRUM);
1361 if !info.images.is_empty() {
1362 Ok("image")
1363 } else if !info.traces.is_empty() && (!short_traces || info.spectra.is_empty()) {
1364 Ok("trace")
1365 } else if !info.spectra.is_empty() {
1366 Ok("spectrum")
1367 } else if !info.tables.is_empty() {
1368 Ok(if events::is_events(info, 0) {
1369 "events"
1370 } else {
1371 "plate"
1372 })
1373 } else {
1374 Err(Error::unsupported(
1375 "preview",
1376 format!("preview of a {} file", info.format.name),
1377 "This file holds no images, traces, spectra or tables to draw; see `openreadout info`.",
1378 ))
1379 }
1380}
1381
1382pub const MAX_ANNOTATIONS: usize = 500;
1384pub const MAX_CHANNELS: usize = 64;
1386pub const MAX_TITLE_CHARS: usize = 300;
1388pub const MAX_CAPTION_CHARS: usize = 2000;
1390
1391fn check_limits(req: &PreviewRequest) -> Result<()> {
1393 if req.max_size < 16 || req.max_size > MAX_PREVIEW_SIZE {
1394 return Err(Error::Usage(format!(
1395 "max size {} is out of range: use 16 to {MAX_PREVIEW_SIZE}",
1396 req.max_size
1397 )));
1398 }
1399 let over = |what: &str, n: usize, max: usize, how: &str| {
1400 Err(Error::Usage(format!(
1401 "{n} {what} are over the limit of {max}; {how}"
1402 )))
1403 };
1404 if req.annotations.len() > MAX_ANNOTATIONS {
1405 return over(
1406 "annotations",
1407 req.annotations.len(),
1408 MAX_ANNOTATIONS,
1409 "mark the most telling ones, or zoom in with region and annotate each part",
1410 );
1411 }
1412 let mut channels = req.channels.clone();
1413 channels.sort_unstable();
1414 channels.dedup();
1415 if channels.len() > MAX_CHANNELS {
1416 return over(
1417 "channels",
1418 channels.len(),
1419 MAX_CHANNELS,
1420 "draw fewer channels per picture",
1421 );
1422 }
1423 for (what, text, max) in [
1424 ("title", &req.title, MAX_TITLE_CHARS),
1425 ("caption", &req.caption, MAX_CAPTION_CHARS),
1426 ] {
1427 let n = text.as_deref().map_or(0, |t| t.chars().count());
1428 if n > max {
1429 return Err(Error::Usage(format!(
1430 "a {what} of {n} characters is over the limit of {max}; shorten it, and give the full text in your reply"
1431 )));
1432 }
1433 }
1434 Ok(())
1435}
1436
1437pub fn render(ds: &mut dyn Dataset, info: &FileInfo, req: &PreviewRequest) -> Result<Rendered> {
1439 check_limits(req)?;
1440 let k = kind(info, req)?;
1441 let mut out = PreviewOutput {
1442 path: info.path.clone(),
1443 format: info.format.id.clone(),
1444 kind: k.into(),
1445 ..PreviewOutput::default()
1446 };
1447 let objects_req = (k == "image")
1448 .then(|| objects::show_counted_channel(info, req, &mut out.notes))
1449 .flatten();
1450 let req = objects_req.as_ref().unwrap_or(req);
1451 let nmr_default = k == "trace"
1453 && info.format.family == "nmr"
1454 && req.trace.is_none()
1455 && req.sweep.is_none()
1456 && req.channels.is_empty();
1457 let seq_default = info.format.family == "sequencing"
1460 && req.table.is_none()
1461 && req.columns.is_empty()
1462 && req.channels.is_empty()
1463 && req.trace.is_none_or(|t| t == 0);
1464 let mut drawn = if nmr_default {
1465 nmr::render(ds, info, req, &mut out)
1466 } else if seq_default {
1467 sequencing::render(ds, info, req, &mut out)
1468 } else {
1469 None
1470 };
1471 if drawn.is_none() && k == "trace" && info.format.family == "electrophoresis" {
1473 drawn = electrophoresis::render(ds, info, req, &mut out)?;
1474 }
1475 if drawn.is_none()
1477 && k == "spectrum"
1478 && req.run.is_none()
1479 && req.spectrum.is_none()
1480 && req.scan.is_none()
1481 && !req.centroid
1482 {
1483 drawn = tic::render(ds, info, req, &mut out)?;
1484 if drawn.is_some() {
1485 out.kind = "chromatogram".into();
1486 }
1487 }
1488 if drawn.is_none() && samples::applies(info, req) {
1489 drawn = Some(samples::render(ds, info, req, &mut out)?);
1490 out.kind = "samples".into();
1491 }
1492 let (mut figure, frame) = match (k, drawn) {
1493 (_, Some(drawn)) => drawn,
1494 ("image", _) => render_image(ds, info, req, &mut out)?,
1495 ("trace", _) if electrochem::is_voltammetry(info, req) => {
1496 electrochem::render(ds, info, req, &mut out)?
1497 }
1498 ("trace", _) => trace::render(ds, info, req, &mut out)?,
1499 ("spectrum", _) => spectrum::render(ds, info, req, &mut out)?,
1500 ("events", _) => events::render(ds, info, req, &mut out)?,
1501 _ => plate::render(ds, info, req, &mut out)?,
1502 };
1503 if out.kind != "image" && (req.title.is_some() || req.caption.is_some()) {
1504 out.notes.push(
1505 "title and caption are drawn on image previews; openreadout_plot titles and captions plots"
1506 .into(),
1507 );
1508 }
1509 if let Frame::Plots { panels, .. } = &frame {
1510 out.panels = panels.iter().map(annotate::plot_panel).collect();
1511 }
1512 if k == "image" && (req.marks == Marks::Objects || req.objects.is_some()) {
1513 objects::draw(ds, info, req, &frame, &mut figure, &mut out)?;
1514 }
1515 if k == "image" && (req.marks == Marks::Lanes || req.lanes.is_some()) {
1516 lanes::draw(ds, info, req, &frame, &mut figure, &mut out);
1517 }
1518 if !req.annotations.is_empty() {
1519 let theme = theme(req);
1520 out.annotations = annotate::draw(
1521 &mut figure,
1522 &frame,
1523 &req.annotations,
1524 &theme,
1525 &mut out.notes,
1526 )?;
1527 }
1528 figure.title = Some(title(&out));
1529 let mut canvas = figure.to_raster(1.0);
1530 while canvas.width.max(canvas.height) > req.max_size {
1532 canvas = canvas.half();
1533 out.halved();
1534 out.notes.push(format!(
1535 "layout larger than max size {}; halved to {}x{}",
1536 req.max_size, canvas.width, canvas.height
1537 ));
1538 }
1539 Ok(Rendered {
1540 canvas,
1541 figure,
1542 output: out,
1543 })
1544}
1545
1546fn title(o: &PreviewOutput) -> String {
1548 let name = Path::new(&o.path)
1549 .file_name()
1550 .map_or_else(|| o.path.clone(), |n| n.to_string_lossy().to_string());
1551 format!("{} preview of {name}", o.kind)
1552}
1553
1554pub fn encode(c: &Raster, encoding: Encoding, jpeg_quality: u8) -> Result<Vec<u8>> {
1557 match encoding {
1558 Encoding::Jpeg => c.to_jpeg(jpeg_quality),
1559 Encoding::Png => c.to_png(),
1560 Encoding::Svg => Err(Error::Usage(
1561 "SVG is drawn from the figure, not a raster; use finish()".into(),
1562 )),
1563 }
1564}
1565
1566pub fn encode_figure(f: &Figure, encoding: Encoding, jpeg_quality: u8) -> Result<Vec<u8>> {
1568 match encoding {
1569 Encoding::Svg => Ok(f.to_svg().into_bytes()),
1570 e => encode(&f.to_raster(1.0), e, jpeg_quality),
1571 }
1572}
1573
1574fn xxh3_hex(b: &[u8]) -> String {
1575 format!("{:032x}", xxhash_rust::xxh3::xxh3_128(b))
1576}
1577
1578pub fn finish(
1580 r: &Rendered,
1581 encoding: Encoding,
1582 jpeg_quality: u8,
1583) -> Result<(PreviewOutput, Vec<u8>)> {
1584 let bytes = match encoding {
1585 Encoding::Svg => r.figure.to_svg().into_bytes(),
1586 e => encode(&r.canvas, e, jpeg_quality)?,
1587 };
1588 let mut out = r.output.clone();
1589 out.encoding = encoding.as_str().into();
1590 out.width = r.canvas.width;
1591 out.height = r.canvas.height;
1592 out.bytes = bytes.len() as u64;
1593 out.xxh3 = xxh3_hex(&bytes);
1594 Ok((out, bytes))
1595}
1596
1597pub fn finish_within(
1602 r: &Rendered,
1603 encoding: Encoding,
1604 jpeg_quality: u8,
1605 max_bytes: usize,
1606) -> Result<(PreviewOutput, Vec<u8>)> {
1607 let (mut out, mut bytes) = finish(r, encoding, jpeg_quality)?;
1608 if bytes.len() <= max_bytes {
1609 return Ok((out, bytes));
1610 }
1611 let mut cur = r.clone();
1612 let mut enc = encoding;
1613 if enc != Encoding::Jpeg {
1614 enc = Encoding::Jpeg;
1615 (out, bytes) = finish(&cur, enc, 85)?;
1616 }
1617 let mut halved = false;
1618 while bytes.len() > max_bytes && cur.canvas.width.max(cur.canvas.height) > 32 {
1619 cur.canvas = cur.canvas.half();
1620 cur.output.halved();
1621 (out, bytes) = finish(&cur, enc, 85)?;
1622 halved = true;
1623 }
1624 if halved {
1625 out.notes.push(format!(
1626 "shown at reduced resolution ({}x{} px); preview a region for full detail",
1627 cur.canvas.width, cur.canvas.height
1628 ));
1629 }
1630 Ok((out, bytes))
1631}
1632
1633pub fn thumbnail(
1639 ds: &mut dyn Dataset,
1640 info: &FileInfo,
1641 max_size: u32,
1642 max_read_bytes: u64,
1643) -> Result<Rendered> {
1644 let im = info.images.first().ok_or_else(|| {
1645 Error::unsupported(
1646 "preview",
1647 "thumbnail of a file without images",
1648 "Use `preview` for traces, spectra and plates.",
1649 )
1650 })?;
1651 let mut req = PreviewRequest {
1652 image: Some(im.index),
1653 max_size,
1654 max_read_bytes: Some(max_read_bytes),
1655 composite: im.samples_per_pixel != 3 && (2..=4).contains(&im.size_c),
1656 ..PreviewRequest::default()
1657 };
1658 match render(ds, info, &req) {
1659 Err(Error::Unsupported { .. }) if req.composite => {
1661 req.composite = false;
1662 render(ds, info, &req)
1663 }
1664 other => other,
1665 }
1666}
1667
1668pub fn default_output(input: &Path, encoding: Encoding) -> PathBuf {
1670 let stem = input
1671 .file_stem()
1672 .map_or_else(|| "preview".into(), |s| s.to_string_lossy().to_string());
1673 input.with_file_name(format!("{stem}.preview.{}", encoding.extension()))
1674}
1675
1676pub fn write_verified(input: &Path, output: &Path, bytes: &[u8], overwrite: bool) -> Result<bool> {
1680 openreadout_core::output::write_verified(output, bytes, overwrite, &[input])?;
1681 Ok(true)
1682}
1683
1684#[cfg(test)]
1685mod tests {
1686 use super::*;
1687
1688 #[test]
1691 fn a_scaled_save_takes_only_the_pixels() {
1692 use std::sync::Arc;
1693 let picture = |w: u32, h: u32, rect: openreadout_figure::Rect| {
1694 let mut figure = Figure::new(rect.w + 20.0, rect.h + 20.0, None);
1695 figure.image(rect, Arc::new(Raster::new(w, h, [9, 9, 9])), false);
1696 figure.text(
1697 5.0,
1698 5.0,
1699 "12 nuclei",
1700 &openreadout_figure::TextStyle::new(12.0, openreadout_figure::Color::rgb(0, 0, 0)),
1701 );
1702 Rendered {
1703 canvas: Raster::new(1, 1, [0, 0, 0]),
1704 figure,
1705 output: PreviewOutput::default(),
1706 }
1707 };
1708 let mut small = picture(
1709 100,
1710 50,
1711 openreadout_figure::Rect::new(10.0, 10.0, 100.0, 50.0),
1712 );
1713 let big = picture(
1714 300,
1715 150,
1716 openreadout_figure::Rect::new(10.0, 10.0, 300.0, 150.0),
1717 );
1718 assert!(small.take_pixels(&big, 3.0));
1719 assert_eq!(small.figure.width, 120.0, "the layout stays the small one");
1720 let sizes: Vec<(u32, u32)> = small
1721 .figure
1722 .items
1723 .iter()
1724 .filter_map(|i| match i {
1725 openreadout_figure::Item::Image { raster, .. } => {
1726 Some((raster.width, raster.height))
1727 }
1728 _ => None,
1729 })
1730 .collect();
1731 assert_eq!(sizes, vec![(300, 150)]);
1732 let mut other = picture(
1733 100,
1734 50,
1735 openreadout_figure::Rect::new(10.0, 10.0, 100.0, 50.0),
1736 );
1737 assert!(!other.take_pixels(
1738 &picture(
1739 120,
1740 50,
1741 openreadout_figure::Rect::new(0.0, 0.0, 120.0, 50.0)
1742 ),
1743 3.0
1744 ));
1745 }
1746
1747 #[test]
1748 fn parses_options() {
1749 assert_eq!("auto".parse::<Contrast>().unwrap(), Contrast::Auto);
1750 assert_eq!(
1751 "percentile:1,99".parse::<Contrast>().unwrap(),
1752 Contrast::Percentile(1.0, 99.0)
1753 );
1754 assert!("percentile:99,1".parse::<Contrast>().is_err());
1755 assert!("bright".parse::<Contrast>().is_err());
1756 assert_eq!("channel-color".parse::<Lut>().unwrap(), Lut::ChannelColor);
1757 assert_eq!("Z".parse::<Axis>().unwrap(), Axis::Z);
1758 assert_eq!("spikes".parse::<Marks>().unwrap(), Marks::Spikes);
1759 assert_eq!(Encoding::from_path(Path::new("a.JPG")), Encoding::Jpeg);
1760 assert_eq!(Encoding::from_path(Path::new("a.svg")), Encoding::Svg);
1761 assert_eq!(Encoding::from_path(Path::new("a")), Encoding::Png);
1762 }
1763
1764 #[test]
1765 fn splits_combined_selection() {
1766 assert_eq!(
1767 split_select(&["c=0,1,z=2".into(), "t=3".into()]),
1768 vec!["c=0,1", "z=2", "t=3"]
1769 );
1770 assert_eq!(split_select(&["z=1-3".into()]), vec!["z=1-3"]);
1771 }
1772}