#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![allow(clippy::many_single_char_names)]
mod annotate;
pub mod color;
mod diffraction;
pub mod electrochem;
mod electrophoresis;
mod events;
mod fft_inset;
mod figure_frame;
mod image;
mod kinetic;
mod lanes;
mod marks;
mod nmr;
mod objects;
mod options;
mod overlay;
mod plate;
mod rulers;
mod samples;
mod sequencing;
mod spectrum;
mod tic;
mod trace;
mod volume;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use openreadout_core::model::FileInfo;
use openreadout_core::reader::Dataset;
use openreadout_core::{Error, Result};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub use annotate::{Annotation, AnnotationType, DrawnAnnotation};
pub use electrophoresis::series_index_of;
pub use openreadout_figure::{Figure, Raster};
pub use options::PreviewOptions;
pub use plate::{PlateGrid, plate_grid};
pub use volume::View;
pub const MAX_PREVIEW_SIZE: u32 = 8192;
pub const DEFAULT_PREVIEW_SIZE: u32 = 1024;
pub const DEFAULT_JPEG_QUALITY: u8 = 90;
pub const DEFAULT_THUMBNAIL_SIZE: u32 = 384;
pub const DEFAULT_THUMBNAIL_READ_BYTES: u64 = 32 << 20;
pub const MIN_TRACE_SAMPLES_OVER_SPECTRUM: u64 = 100;
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum Contrast {
#[default]
Auto,
MinMax,
Percentile(f64, f64),
Raw,
Window(f64, f64),
StoredWindow(usize),
Log(f64, f64),
}
pub const WINDOW_PRESETS: &[(&str, f64, f64)] = &[
("soft-tissue", 40.0, 400.0),
("brain", 40.0, 80.0),
("subdural", 75.0, 215.0),
("stroke", 40.0, 40.0),
("bone", 400.0, 1800.0),
("lung", -600.0, 1500.0),
("mediastinum", 50.0, 350.0),
("liver", 60.0, 150.0),
];
pub const LOG_PERCENTILES: (f64, f64) = (50.0, 99.9);
impl FromStr for Contrast {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s = s.trim().to_ascii_lowercase();
match s.as_str() {
"auto" => Ok(Contrast::Auto),
"min-max" | "minmax" => Ok(Contrast::MinMax),
"raw" => Ok(Contrast::Raw),
"log" => Ok(Contrast::Log(LOG_PERCENTILES.0, LOG_PERCENTILES.1)),
_ if s.starts_with("window") => {
let bad = || {
let names: Vec<&str> = WINDOW_PRESETS.iter().map(|p| p.0).collect();
Error::Usage(format!(
"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:{}",
names.join(", window:")
))
};
let spec = s.strip_prefix("window:").ok_or_else(bad)?.trim();
if let Some(rest) = spec.strip_prefix("file") {
let n = match rest.strip_prefix(':') {
Some(n) => n.trim().parse().map_err(|_| bad())?,
None if rest.is_empty() => 0,
None => return Err(bad()),
};
return Ok(Contrast::StoredWindow(n));
}
if let Some((_, c, w)) = WINDOW_PRESETS
.iter()
.find(|p| p.0 == spec.replace('_', "-"))
{
return Ok(Contrast::Window(*c, *w));
}
let (c, w) = spec.split_once(',').ok_or_else(bad)?;
let (c, w): (f64, f64) = (
c.trim().parse().map_err(|_| bad())?,
w.trim().parse().map_err(|_| bad())?,
);
if !c.is_finite() || !w.is_finite() || w <= 0.0 {
return Err(bad());
}
Ok(Contrast::Window(c, w))
}
_ => {
let bad = || {
Error::Usage(format!(
"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, ...)"
))
};
let (log, spec) = match s.strip_prefix("log:") {
Some(rest) => (true, rest),
None => (false, s.strip_prefix("percentile:").ok_or_else(bad)?),
};
let (a, b) = spec.split_once(',').ok_or_else(bad)?;
let (a, b): (f64, f64) = (
a.trim().parse().map_err(|_| bad())?,
b.trim().parse().map_err(|_| bad())?,
);
if !(0.0..=100.0).contains(&a) || !(0.0..=100.0).contains(&b) || a >= b {
return Err(bad());
}
Ok(if log {
Contrast::Log(a, b)
} else {
Contrast::Percentile(a, b)
})
}
}
}
}
impl std::fmt::Display for Contrast {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Contrast::Auto => f.write_str("auto"),
Contrast::MinMax => f.write_str("min-max"),
Contrast::Percentile(a, b) => write!(f, "percentile:{a},{b}"),
Contrast::Raw => f.write_str("raw"),
Contrast::Window(c, w) => write!(f, "window:{c},{w}"),
Contrast::StoredWindow(n) => write!(f, "window:file:{n}"),
Contrast::Log(a, b) => write!(f, "log:{a},{b}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Lut {
#[serde(alias = "grey")]
Gray,
#[serde(alias = "channel-colour", alias = "color")]
ChannelColor,
Inverted,
}
impl FromStr for Lut {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"gray" | "grey" => Ok(Lut::Gray),
"channel-color" | "channel-colour" | "color" => Ok(Lut::ChannelColor),
"inverted" => Ok(Lut::Inverted),
other => Err(Error::Usage(format!(
"bad lut '{other}': use gray, inverted or channel-color"
))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Axis {
Z,
T,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Default,
serde::Deserialize,
serde::Serialize,
schemars::JsonSchema,
)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Axes {
#[default]
Rulers,
Grid,
ScaleBar,
None,
}
impl Axes {
pub fn apply(self, req: &mut PreviewRequest) {
req.axes = self != Axes::None;
req.grid = self == Axes::Grid;
req.figure = self == Axes::ScaleBar;
}
}
impl FromStr for Axes {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
"rulers" => Ok(Axes::Rulers),
"grid" => Ok(Axes::Grid),
"scale-bar" | "scalebar" => Ok(Axes::ScaleBar),
"none" => Ok(Axes::None),
other => Err(Error::Usage(format!(
"bad axes '{other}': use rulers, grid, scale-bar or none"
))),
}
}
}
impl FromStr for Axis {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"z" => Ok(Axis::Z),
"t" => Ok(Axis::T),
other => Err(Error::Usage(format!(
"bad projection axis '{other}': use z or t"
))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Encoding {
#[default]
Png,
#[serde(alias = "jpg")]
Jpeg,
Svg,
}
impl Encoding {
pub fn as_str(self) -> &'static str {
match self {
Encoding::Png => "png",
Encoding::Jpeg => "jpeg",
Encoding::Svg => "svg",
}
}
pub fn mime(self) -> &'static str {
match self {
Encoding::Png => "image/png",
Encoding::Jpeg => "image/jpeg",
Encoding::Svg => "image/svg+xml",
}
}
pub fn extension(self) -> &'static str {
match self {
Encoding::Png => "png",
Encoding::Jpeg => "jpg",
Encoding::Svg => "svg",
}
}
pub fn from_path(p: &Path) -> Self {
match p
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase)
.as_deref()
{
Some("jpg" | "jpeg") => Encoding::Jpeg,
Some("svg") => Encoding::Svg,
_ => Encoding::Png,
}
}
}
impl FromStr for Encoding {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"png" => Ok(Encoding::Png),
"jpeg" | "jpg" => Ok(Encoding::Jpeg),
"svg" => Ok(Encoding::Svg),
other => Err(Error::Usage(format!(
"bad preview format '{other}': use png, jpeg or svg"
))),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Marks {
#[default]
Auto,
Peaks,
Spikes,
Objects,
Lanes,
Rings,
None,
}
impl FromStr for Marks {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"auto" => Ok(Marks::Auto),
"peaks" => Ok(Marks::Peaks),
"spikes" => Ok(Marks::Spikes),
"objects" => Ok(Marks::Objects),
"lanes" => Ok(Marks::Lanes),
"rings" => Ok(Marks::Rings),
"none" => Ok(Marks::None),
other => Err(Error::Usage(format!(
"bad marks '{other}': use auto, peaks, spikes, objects, lanes, rings or none"
))),
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PreviewRequest {
pub image: Option<u32>,
pub select: Vec<String>,
pub mip: Option<Axis>,
pub view: Option<View>,
pub sum: Option<Axis>,
pub fft: bool,
pub composite: bool,
pub level: Option<u32>,
pub region: Option<openreadout_core::Region>,
pub max_size: u32,
pub contrast: Contrast,
pub lut: Option<Lut>,
pub trace: Option<u32>,
pub sweep: Option<u32>,
pub channels: Vec<u32>,
pub x_range: Option<[f64; 2]>,
pub run: Option<u32>,
pub spectrum: Option<u64>,
pub scan: Option<u64>,
pub centroid: bool,
pub table: Option<u32>,
pub columns: Vec<String>,
pub marks: Marks,
pub objects: Option<openreadout_core::measure::ObjectsRequest>,
pub lanes: Option<openreadout_core::measure::LanesRequest>,
pub annotations: Vec<Annotation>,
pub dark: bool,
pub axes: bool,
pub grid: bool,
pub figure: bool,
pub title: Option<String>,
pub caption: Option<String>,
pub max_read_bytes: Option<u64>,
}
impl Default for PreviewRequest {
fn default() -> Self {
PreviewRequest {
image: None,
select: Vec::new(),
mip: None,
view: None,
sum: None,
fft: false,
composite: false,
level: None,
region: None,
max_size: DEFAULT_PREVIEW_SIZE,
contrast: Contrast::Auto,
lut: None,
trace: None,
sweep: None,
channels: Vec::new(),
x_range: None,
run: None,
spectrum: None,
scan: None,
centroid: false,
table: None,
columns: Vec::new(),
marks: Marks::Auto,
objects: None,
lanes: None,
annotations: Vec::new(),
dark: false,
axes: true,
grid: false,
figure: false,
title: None,
caption: None,
max_read_bytes: None,
}
}
}
fn render_image(
ds: &mut dyn Dataset,
info: &FileInfo,
req: &PreviewRequest,
out: &mut PreviewOutput,
) -> Result<(Figure, Frame)> {
let image = req.image.unwrap_or(0);
let Some(im) = info.images.iter().find(|i| i.index == image) else {
return image::render(ds, info, req, out);
};
let Some(view) = volume::effective(info, im, req.view) else {
return image::render(ds, info, req, out);
};
let sel = openreadout_core::select::Selection::parse(&split_select(&req.select))?;
let mut req = req.clone();
let select_z = sel.z.first().copied();
if view == View::Orthogonal {
let join = |a: &str, v: &[u32]| {
(!v.is_empty()).then(|| {
format!(
"{a}={}",
v.iter().map(u32::to_string).collect::<Vec<_>>().join(",")
)
})
};
req.select = [join("c", &sel.c), join("t", &sel.t)]
.into_iter()
.flatten()
.collect();
if req.mip.is_some() {
return Err(Error::Usage(
"an orthogonal view shows three slices; project with view axial, coronal or sagittal and mip z".into(),
));
}
if req.axes && !req.figure {
req.figure = true;
req.grid = false;
out.notes
.push("orthogonal views are framed with a scale bar, not rulers".into());
}
}
let (mut vds, vim, marks, notes) = volume::ViewDataset::new(ds, info, image, view, select_z)?;
out.notes.extend(notes);
let slices = vim.size_z;
let mut vinfo = info.clone();
if let Some(slot) = vinfo.images.iter_mut().find(|i| i.index == image) {
*slot = vim;
}
let (mut figure, frame) = image::render(&mut vds, &vinfo, &req, out)?;
if !marks.is_empty() {
let theme = theme(&req);
annotate::draw(&mut figure, &frame, &marks, &theme, &mut Vec::new())?;
}
let drawn = (figure, frame);
if let Some(p) = out.image.as_mut() {
p.view = Some(
match vds.view() {
View::Axial => "axial",
View::Coronal => "coronal",
View::Sagittal => "sagittal",
View::Orthogonal => "orthogonal",
View::Xz => "xz",
View::Yz => "yz",
View::Native => "native",
}
.into(),
);
p.crosshair = vds.point();
p.view_slices = Some(slices);
}
if req.view.is_none() {
out.notes.push(format!(
"shown as a radiological {} view (view: native shows the stored orientation)",
out.image
.as_ref()
.and_then(|p| p.view.clone())
.unwrap_or_default()
));
}
let _ = vds.ortho_step();
Ok(drawn)
}
pub(crate) fn theme(req: &PreviewRequest) -> openreadout_figure::Theme {
let t = if req.dark {
openreadout_figure::Theme::dark()
} else {
openreadout_figure::Theme::light()
};
t.for_size(req.max_size as f32)
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct PreviewChannel {
pub index: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub color: String,
pub color_source: String,
pub display_min: f64,
pub display_max: f64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SourcePoint {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ScaleBar {
pub length: f64,
pub unit: String,
pub length_um: f64,
pub pixels: u32,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ImagePreview {
pub image: u32,
pub level: u32,
pub source_width: u32,
pub source_height: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<openreadout_core::Region>,
pub downsample: f64,
pub c: Vec<u32>,
pub z: Vec<u32>,
pub t: Vec<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub projection: Option<String>,
pub composite: bool,
pub rgb: bool,
pub contrast: String,
pub lut: String,
pub channels: Vec<PreviewChannel>,
#[serde(default)]
pub axes: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub grid: bool,
#[serde(default)]
pub plot_area: openreadout_core::Region,
#[serde(default)]
pub source_origin: SourcePoint,
#[serde(default)]
pub source_per_pixel: f64,
#[serde(default)]
pub source_per_pixel_y: f64,
#[serde(default)]
pub full_res_region: openreadout_core::Region,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fft_inset: Option<openreadout_core::Region>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scale_bar: Option<ScaleBar>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub crosshair: Option<[u32; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view_slices: Option<u32>,
}
impl ImagePreview {
pub fn pixel_mapping(&self) -> String {
let n = |v: f64| {
let s = format!("{v:.3}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
};
let term = |origin: f64, edge: u32, per: f64, p: &str| {
let at = if edge == 0 {
p.to_string()
} else {
format!("({p} − {edge})")
};
if origin == 0.0 {
format!("{at} × {}", n(per))
} else {
format!("{} + {at} × {}", n(origin), n(per))
}
};
format!(
"this picture has no rulers: picture pixel (px, py) is full-res x = {}, y = {}",
term(
self.source_origin.x,
self.plot_area.x,
self.source_per_pixel,
"px"
),
term(
self.source_origin.y,
self.plot_area.y,
self.source_per_pixel_y,
"py"
),
)
}
fn halve(&mut self) {
let (plot, origin, per) = rulers::halve(
self.plot_area,
self.source_origin,
(self.source_per_pixel, self.source_per_pixel_y),
);
self.plot_area = plot;
self.source_origin = origin;
(self.source_per_pixel, self.source_per_pixel_y) = per;
if let Some(b) = &mut self.scale_bar {
b.pixels = b.pixels.div_ceil(2);
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct TracePreviewChannel {
pub index: u32,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
pub color: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub min: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max: Option<f64>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct XAxis {
pub quantity: String,
pub unit: String,
pub first: f64,
pub last: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct TracePreview {
pub trace: u32,
pub sweep: u32,
pub sample_rate_hz: f64,
pub sweep_sample_count: u64,
pub sample_count: u64,
pub truncated: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub x_axis: Option<XAxis>,
pub channels: Vec<TracePreviewChannel>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SpectrumPreview {
pub run: u32,
pub index: u64,
pub scan_number: u64,
pub ms_level: u32,
pub rt_s: Option<f64>,
pub style: String,
pub point_count: u64,
pub x_axis: XAxis,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_intensity: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub precursor_mz: Option<f64>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ChromatogramPreview {
pub run: u32,
pub signal: String,
pub ms1_scans: u64,
pub scans: u64,
pub apex_rt_min: f64,
pub apex_intensity: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct PlateGroup {
pub name: String,
pub color: String,
pub wells: u32,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub blank: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct PlatePreview {
pub table: u32,
pub layout: String,
pub view: String,
pub rows: u32,
pub columns: u32,
pub wells: u32,
pub value: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub min: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub time: Option<[f64; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub time_unit: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grouped_by: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<PlateGroup>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct EventsPreview {
pub table: u32,
pub x: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub y: Option<String>,
pub events: u64,
pub total_events: u64,
pub scales: Vec<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct PlotPanel {
pub plot_area: PxRect,
pub x: [f64; 2],
pub y: [f64; 2],
pub x_scale: String,
pub y_scale: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub well: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct PxRect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl From<openreadout_figure::Rect> for PxRect {
fn from(r: openreadout_figure::Rect) -> Self {
let q = |v: f32| (f64::from(v) * 100.0).round() / 100.0;
PxRect {
x: q(r.x),
y: q(r.y),
width: q(r.w),
height: q(r.h),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DataMark {
pub kind: String,
pub x: f64,
pub y: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel: Option<u32>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct PreviewOutput {
pub path: String,
pub format: String,
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub output: Option<String>,
pub encoding: String,
pub width: u32,
pub height: u32,
pub bytes: u64,
pub xxh3: String,
pub verified: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub image: Option<ImagePreview>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trace: Option<TracePreview>,
#[serde(skip_serializing_if = "Option::is_none")]
pub spectrum: Option<SpectrumPreview>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub chromatogram: Option<ChromatogramPreview>,
#[serde(skip_serializing_if = "Option::is_none")]
pub plate: Option<PlatePreview>,
#[serde(skip_serializing_if = "Option::is_none")]
pub events: Option<EventsPreview>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub panels: Vec<PlotPanel>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub marks: Vec<DataMark>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
pub objects: Option<openreadout_core::measure::Objects>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")]
pub lanes: Option<openreadout_core::measure::Lanes>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub annotations: Vec<DrawnAnnotation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub save: Option<String>,
}
impl PreviewOutput {
fn halved(&mut self) {
if let Some(im) = &mut self.image {
im.halve();
}
let h = |r: &mut PxRect| {
r.x /= 2.0;
r.y /= 2.0;
r.width /= 2.0;
r.height /= 2.0;
};
for p in &mut self.panels {
h(&mut p.plot_area);
}
for a in &mut self.annotations {
a.halve();
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum Frame {
Image {
plot_area: openreadout_core::Region,
map: rulers::Mapping,
},
Plots {
panels: Vec<FramePanel>,
key: Option<KeySlot>,
taken: Vec<openreadout_figure::Rect>,
},
Wells(Vec<((u32, u32), openreadout_figure::Rect)>),
}
impl Frame {
pub(crate) fn plots(panels: Vec<FramePanel>) -> Frame {
Frame::Plots {
panels,
key: None,
taken: Vec::new(),
}
}
pub(crate) fn plots_labelled(
panels: Vec<FramePanel>,
taken: &[openreadout_figure::Rect],
) -> Frame {
Frame::Plots {
panels,
key: None,
taken: taken.to_vec(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct KeySlot {
pub x: f32,
pub y: f32,
pub max_x: f32,
}
#[derive(Debug, Clone)]
pub(crate) struct FramePanel {
pub panel: openreadout_figure::Panel,
pub channel: Option<u32>,
pub well: Option<(u32, u32)>,
}
impl FramePanel {
pub(crate) fn new(panel: openreadout_figure::Panel) -> Self {
FramePanel {
panel,
channel: None,
well: None,
}
}
}
#[derive(Debug, Clone)]
pub struct Rendered {
pub canvas: Raster,
pub figure: Figure,
pub output: PreviewOutput,
}
impl Rendered {
pub fn take_pixels(&mut self, big: &Rendered, scale: f32) -> bool {
use openreadout_figure::Item;
fn largest(f: &Figure) -> Option<usize> {
f.items
.iter()
.enumerate()
.filter_map(|(i, it)| match it {
Item::Image { rect, .. } => Some((i, rect.w * rect.h)),
_ => None,
})
.max_by(|a, b| a.1.total_cmp(&b.1))
.map(|x| x.0)
}
let (Some(i), Some(j)) = (largest(&self.figure), largest(&big.figure)) else {
return false;
};
let Item::Image { raster, .. } = &big.figure.items[j] else {
return false;
};
let raster = raster.clone();
let Item::Image {
rect,
raster: mine,
smooth,
} = &mut self.figure.items[i]
else {
return false;
};
let (w, h) = (raster.width as f32, raster.height as f32);
let same_shape = (w / h - rect.w / rect.h).abs() <= 0.02 * rect.w / rect.h;
if !same_shape || w <= mine.width as f32 {
return false;
}
if (w - rect.w * scale).abs() > 1.0 {
*smooth = true;
}
*mine = raster;
true
}
}
pub fn split_select(args: &[String]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for a in args {
let mut cur = String::new();
for part in a.split(',') {
if part.contains('=') && !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
if !cur.is_empty() {
cur.push(',');
}
cur.push_str(part.trim());
}
if !cur.is_empty() {
out.push(cur);
}
}
out
}
fn kind(info: &FileInfo, req: &PreviewRequest) -> Result<&'static str> {
if req.table.is_some() || !req.columns.is_empty() {
return Ok(if events::is_events(info, req.table.unwrap_or(0)) {
"events"
} else {
"plate"
});
}
if req.trace.is_some()
|| req.sweep.is_some()
|| !req.channels.is_empty()
|| req.x_range.is_some()
{
return Ok("trace");
}
if req.run.is_some() || req.spectrum.is_some() || req.scan.is_some() || req.centroid {
return Ok("spectrum");
}
let short_traces = info
.traces
.iter()
.all(|t| t.sample_count < MIN_TRACE_SAMPLES_OVER_SPECTRUM);
if !info.images.is_empty() {
Ok("image")
} else if !info.traces.is_empty() && (!short_traces || info.spectra.is_empty()) {
Ok("trace")
} else if !info.spectra.is_empty() {
Ok("spectrum")
} else if !info.tables.is_empty() {
Ok(if events::is_events(info, 0) {
"events"
} else {
"plate"
})
} else {
Err(Error::unsupported(
"preview",
format!("preview of a {} file", info.format.name),
"This file holds no images, traces, spectra or tables to draw; see `openreadout info`.",
))
}
}
pub const MAX_ANNOTATIONS: usize = 500;
pub const MAX_CHANNELS: usize = 64;
pub const MAX_TITLE_CHARS: usize = 300;
pub const MAX_CAPTION_CHARS: usize = 2000;
fn check_limits(req: &PreviewRequest) -> Result<()> {
if req.max_size < 16 || req.max_size > MAX_PREVIEW_SIZE {
return Err(Error::Usage(format!(
"max size {} is out of range: use 16 to {MAX_PREVIEW_SIZE}",
req.max_size
)));
}
let over = |what: &str, n: usize, max: usize, how: &str| {
Err(Error::Usage(format!(
"{n} {what} are over the limit of {max}; {how}"
)))
};
if req.annotations.len() > MAX_ANNOTATIONS {
return over(
"annotations",
req.annotations.len(),
MAX_ANNOTATIONS,
"mark the most telling ones, or zoom in with region and annotate each part",
);
}
let mut channels = req.channels.clone();
channels.sort_unstable();
channels.dedup();
if channels.len() > MAX_CHANNELS {
return over(
"channels",
channels.len(),
MAX_CHANNELS,
"draw fewer channels per picture",
);
}
for (what, text, max) in [
("title", &req.title, MAX_TITLE_CHARS),
("caption", &req.caption, MAX_CAPTION_CHARS),
] {
let n = text.as_deref().map_or(0, |t| t.chars().count());
if n > max {
return Err(Error::Usage(format!(
"a {what} of {n} characters is over the limit of {max}; shorten it, and give the full text in your reply"
)));
}
}
Ok(())
}
pub fn render(ds: &mut dyn Dataset, info: &FileInfo, req: &PreviewRequest) -> Result<Rendered> {
check_limits(req)?;
let k = kind(info, req)?;
let mut out = PreviewOutput {
path: info.path.clone(),
format: info.format.id.clone(),
kind: k.into(),
..PreviewOutput::default()
};
let objects_req = (k == "image")
.then(|| objects::show_counted_channel(info, req, &mut out.notes))
.flatten();
let req = objects_req.as_ref().unwrap_or(req);
let nmr_default = k == "trace"
&& info.format.family == "nmr"
&& req.trace.is_none()
&& req.sweep.is_none()
&& req.channels.is_empty();
let seq_default = info.format.family == "sequencing"
&& req.table.is_none()
&& req.columns.is_empty()
&& req.channels.is_empty()
&& req.trace.is_none_or(|t| t == 0);
let mut drawn = if nmr_default {
nmr::render(ds, info, req, &mut out)
} else if seq_default {
sequencing::render(ds, info, req, &mut out)
} else {
None
};
if drawn.is_none() && k == "trace" && info.format.family == "electrophoresis" {
drawn = electrophoresis::render(ds, info, req, &mut out)?;
}
if drawn.is_none()
&& k == "spectrum"
&& req.run.is_none()
&& req.spectrum.is_none()
&& req.scan.is_none()
&& !req.centroid
{
drawn = tic::render(ds, info, req, &mut out)?;
if drawn.is_some() {
out.kind = "chromatogram".into();
}
}
if drawn.is_none() && samples::applies(info, req) {
drawn = Some(samples::render(ds, info, req, &mut out)?);
out.kind = "samples".into();
}
let (mut figure, frame) = match (k, drawn) {
(_, Some(drawn)) => drawn,
("image", _) => render_image(ds, info, req, &mut out)?,
("trace", _) if electrochem::is_voltammetry(info, req) => {
electrochem::render(ds, info, req, &mut out)?
}
("trace", _) => trace::render(ds, info, req, &mut out)?,
("spectrum", _) => spectrum::render(ds, info, req, &mut out)?,
("events", _) => events::render(ds, info, req, &mut out)?,
_ => plate::render(ds, info, req, &mut out)?,
};
if out.kind != "image" && (req.title.is_some() || req.caption.is_some()) {
out.notes.push(
"title and caption are drawn on image previews; openreadout_plot titles and captions plots"
.into(),
);
}
if let Frame::Plots { panels, .. } = &frame {
out.panels = panels.iter().map(annotate::plot_panel).collect();
}
if k == "image" && (req.marks == Marks::Objects || req.objects.is_some()) {
objects::draw(ds, info, req, &frame, &mut figure, &mut out)?;
}
if k == "image" && (req.marks == Marks::Lanes || req.lanes.is_some()) {
lanes::draw(ds, info, req, &frame, &mut figure, &mut out);
}
if !req.annotations.is_empty() {
let theme = theme(req);
out.annotations = annotate::draw(
&mut figure,
&frame,
&req.annotations,
&theme,
&mut out.notes,
)?;
}
figure.title = Some(title(&out));
let mut canvas = figure.to_raster(1.0);
while canvas.width.max(canvas.height) > req.max_size {
canvas = canvas.half();
out.halved();
out.notes.push(format!(
"layout larger than max size {}; halved to {}x{}",
req.max_size, canvas.width, canvas.height
));
}
Ok(Rendered {
canvas,
figure,
output: out,
})
}
fn title(o: &PreviewOutput) -> String {
let name = Path::new(&o.path)
.file_name()
.map_or_else(|| o.path.clone(), |n| n.to_string_lossy().to_string());
format!("{} preview of {name}", o.kind)
}
pub fn encode(c: &Raster, encoding: Encoding, jpeg_quality: u8) -> Result<Vec<u8>> {
match encoding {
Encoding::Jpeg => c.to_jpeg(jpeg_quality),
Encoding::Png => c.to_png(),
Encoding::Svg => Err(Error::Usage(
"SVG is drawn from the figure, not a raster; use finish()".into(),
)),
}
}
pub fn encode_figure(f: &Figure, encoding: Encoding, jpeg_quality: u8) -> Result<Vec<u8>> {
match encoding {
Encoding::Svg => Ok(f.to_svg().into_bytes()),
e => encode(&f.to_raster(1.0), e, jpeg_quality),
}
}
fn xxh3_hex(b: &[u8]) -> String {
format!("{:032x}", xxhash_rust::xxh3::xxh3_128(b))
}
pub fn finish(
r: &Rendered,
encoding: Encoding,
jpeg_quality: u8,
) -> Result<(PreviewOutput, Vec<u8>)> {
let bytes = match encoding {
Encoding::Svg => r.figure.to_svg().into_bytes(),
e => encode(&r.canvas, e, jpeg_quality)?,
};
let mut out = r.output.clone();
out.encoding = encoding.as_str().into();
out.width = r.canvas.width;
out.height = r.canvas.height;
out.bytes = bytes.len() as u64;
out.xxh3 = xxh3_hex(&bytes);
Ok((out, bytes))
}
pub fn finish_within(
r: &Rendered,
encoding: Encoding,
jpeg_quality: u8,
max_bytes: usize,
) -> Result<(PreviewOutput, Vec<u8>)> {
let (mut out, mut bytes) = finish(r, encoding, jpeg_quality)?;
if bytes.len() <= max_bytes {
return Ok((out, bytes));
}
let mut cur = r.clone();
let mut enc = encoding;
if enc != Encoding::Jpeg {
enc = Encoding::Jpeg;
(out, bytes) = finish(&cur, enc, 85)?;
}
let mut halved = false;
while bytes.len() > max_bytes && cur.canvas.width.max(cur.canvas.height) > 32 {
cur.canvas = cur.canvas.half();
cur.output.halved();
(out, bytes) = finish(&cur, enc, 85)?;
halved = true;
}
if halved {
out.notes.push(format!(
"shown at reduced resolution ({}x{} px); preview a region for full detail",
cur.canvas.width, cur.canvas.height
));
}
Ok((out, bytes))
}
pub fn thumbnail(
ds: &mut dyn Dataset,
info: &FileInfo,
max_size: u32,
max_read_bytes: u64,
) -> Result<Rendered> {
let im = info.images.first().ok_or_else(|| {
Error::unsupported(
"preview",
"thumbnail of a file without images",
"Use `preview` for traces, spectra and plates.",
)
})?;
let mut req = PreviewRequest {
image: Some(im.index),
max_size,
max_read_bytes: Some(max_read_bytes),
composite: im.samples_per_pixel != 3 && (2..=4).contains(&im.size_c),
..PreviewRequest::default()
};
match render(ds, info, &req) {
Err(Error::Unsupported { .. }) if req.composite => {
req.composite = false;
render(ds, info, &req)
}
other => other,
}
}
pub fn default_output(input: &Path, encoding: Encoding) -> PathBuf {
let stem = input
.file_stem()
.map_or_else(|| "preview".into(), |s| s.to_string_lossy().to_string());
input.with_file_name(format!("{stem}.preview.{}", encoding.extension()))
}
pub fn write_verified(input: &Path, output: &Path, bytes: &[u8], overwrite: bool) -> Result<bool> {
openreadout_core::output::write_verified(output, bytes, overwrite, &[input])?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_scaled_save_takes_only_the_pixels() {
use std::sync::Arc;
let picture = |w: u32, h: u32, rect: openreadout_figure::Rect| {
let mut figure = Figure::new(rect.w + 20.0, rect.h + 20.0, None);
figure.image(rect, Arc::new(Raster::new(w, h, [9, 9, 9])), false);
figure.text(
5.0,
5.0,
"12 nuclei",
&openreadout_figure::TextStyle::new(12.0, openreadout_figure::Color::rgb(0, 0, 0)),
);
Rendered {
canvas: Raster::new(1, 1, [0, 0, 0]),
figure,
output: PreviewOutput::default(),
}
};
let mut small = picture(
100,
50,
openreadout_figure::Rect::new(10.0, 10.0, 100.0, 50.0),
);
let big = picture(
300,
150,
openreadout_figure::Rect::new(10.0, 10.0, 300.0, 150.0),
);
assert!(small.take_pixels(&big, 3.0));
assert_eq!(small.figure.width, 120.0, "the layout stays the small one");
let sizes: Vec<(u32, u32)> = small
.figure
.items
.iter()
.filter_map(|i| match i {
openreadout_figure::Item::Image { raster, .. } => {
Some((raster.width, raster.height))
}
_ => None,
})
.collect();
assert_eq!(sizes, vec![(300, 150)]);
let mut other = picture(
100,
50,
openreadout_figure::Rect::new(10.0, 10.0, 100.0, 50.0),
);
assert!(!other.take_pixels(
&picture(
120,
50,
openreadout_figure::Rect::new(0.0, 0.0, 120.0, 50.0)
),
3.0
));
}
#[test]
fn parses_options() {
assert_eq!("auto".parse::<Contrast>().unwrap(), Contrast::Auto);
assert_eq!(
"percentile:1,99".parse::<Contrast>().unwrap(),
Contrast::Percentile(1.0, 99.0)
);
assert!("percentile:99,1".parse::<Contrast>().is_err());
assert!("bright".parse::<Contrast>().is_err());
assert_eq!("channel-color".parse::<Lut>().unwrap(), Lut::ChannelColor);
assert_eq!("Z".parse::<Axis>().unwrap(), Axis::Z);
assert_eq!("spikes".parse::<Marks>().unwrap(), Marks::Spikes);
assert_eq!(Encoding::from_path(Path::new("a.JPG")), Encoding::Jpeg);
assert_eq!(Encoding::from_path(Path::new("a.svg")), Encoding::Svg);
assert_eq!(Encoding::from_path(Path::new("a")), Encoding::Png);
}
#[test]
fn splits_combined_selection() {
assert_eq!(
split_select(&["c=0,1,z=2".into(), "t=3".into()]),
vec!["c=0,1", "z=2", "t=3"]
);
assert_eq!(split_select(&["z=1-3".into()]), vec!["z=1-3"]);
}
}