Skip to main content

openreadout_quant/
plot.rs

1//! Pictures of chromatograms, optionally with their integrated peaks shaded, baselines drawn
2//! and peaks numbered at their apex: the picture a chromatographer checks an integration
3//! against. Drawn with the figure engine; deterministic: the same input gives the same bytes.
4
5use openreadout_figure::{
6    Anchor, AxesSpec, Baseline, Domain, Face, Figure, Panel, Path, ScaleKind, Stroke, TextStyle,
7    Theme,
8};
9
10use crate::analyze::ChromatogramPeaks;
11use crate::extract::Chromatogram;
12
13/// Height of one chromatogram panel, pixels.
14pub const PANEL_HEIGHT: u32 = 280;
15
16/// Peaks smaller than this share of the tallest one get no number (they are flat at the
17/// figure's scale; the peak table lists them all).
18const VISIBLE_SHARE: f64 = 0.02;
19
20/// Draw the chromatograms, one panel each, `width` pixels wide. `peaks[k]`, when present, is
21/// drawn over panel `k`.
22pub fn render(chroms: &[Chromatogram], peaks: &[Option<&ChromatogramPeaks>], width: u32) -> Figure {
23    render_labelled(chroms, peaks, &[], width)
24}
25
26/// [`render`] with an x-axis title per panel (`x_labels[k]`; `retention time (min)` where none
27/// is given), for spectra drawn the same way.
28pub fn render_labelled(
29    chroms: &[Chromatogram],
30    peaks: &[Option<&ChromatogramPeaks>],
31    x_labels: &[String],
32    width: u32,
33) -> Figure {
34    let width = width.clamp(200, 8192) as f32;
35    let theme = Theme::light().for_size(width.min(1400.0));
36    let n = chroms.len().max(1);
37    let ph = PANEL_HEIGHT as f32;
38    let mut fig = Figure::new(width, ph * n as f32, Some(theme.paper));
39    for (k, ch) in chroms.iter().enumerate() {
40        let label = x_labels
41            .get(k)
42            .map_or("retention time (min)", String::as_str);
43        let area = openreadout_figure::Rect::new(0.0, ph * k as f32, width, ph);
44        panel(
45            &mut fig,
46            &theme,
47            ch,
48            peaks.get(k).copied().flatten(),
49            area,
50            k,
51            label,
52        );
53    }
54    fig
55}
56
57fn panel(
58    fig: &mut Figure,
59    theme: &Theme,
60    ch: &Chromatogram,
61    pk: Option<&ChromatogramPeaks>,
62    area: openreadout_figure::Rect,
63    k: usize,
64    x_label: &str,
65) {
66    let fs = theme.font_size;
67    let title = format!(
68        "{}{}",
69        ch.label,
70        ch.intensity_unit
71            .as_deref()
72            .map(|u| format!(" ({u})"))
73            .unwrap_or_default()
74    );
75    let pts: Vec<(f64, f64)> = ch
76        .rt_min
77        .iter()
78        .zip(&ch.intensity)
79        .filter(|(t, y)| t.is_finite() && y.is_finite())
80        .map(|(t, y)| (*t, *y))
81        .collect();
82    let title_style = TextStyle::new(fs, theme.ink).align(Anchor::Start, Baseline::Alphabetic);
83    if pts.len() < 2 {
84        fig.text(area.x + fs, area.y + fs * 1.6, &title, &title_style);
85        fig.text(
86            area.x + fs,
87            area.y + area.h / 2.0,
88            "no data",
89            &TextStyle::new(fs, theme.muted),
90        );
91        return;
92    }
93    let (tmin, tmax) = (pts[0].0, pts[pts.len() - 1].0);
94    let ymax = pts.iter().fold(f64::NEG_INFINITY, |m, p| m.max(p.1));
95    let ymin = pts.iter().fold(0.0f64, |m, p| m.min(p.1));
96    let spec = AxesSpec {
97        x_label: Some(x_label.to_string()),
98        y_ticks: 4,
99        top: fs * 1.4,
100        ..AxesSpec::default()
101    };
102    let y_dom = Domain::of([ymin, ymax + (ymax - ymin) * 0.1], 0.0, ScaleKind::Linear);
103    let p = Panel::fit(
104        area.inset(fs * 0.8),
105        Domain::linear(tmin, tmax),
106        y_dom,
107        theme,
108        &spec,
109    );
110    fig.text(area.x + fs * 0.8, area.y + fs * 1.6, &title, &title_style);
111    p.axes(fig, theme, &spec);
112    // signal value at time t (linear interpolation)
113    let at = |t: f64| -> f64 {
114        let i = pts.partition_point(|p| p.0 < t);
115        if i == 0 {
116            return pts[0].1;
117        }
118        if i >= pts.len() {
119            return pts[pts.len() - 1].1;
120        }
121        let (a, b) = (pts[i - 1], pts[i]);
122        if b.0 == a.0 {
123            b.1
124        } else {
125            a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0)
126        }
127    };
128    let fills = [theme.band, theme.accent.alpha(0.18)];
129    if let Some(pk) = pk {
130        for (j, pe) in pk.peaks.iter().enumerate() {
131            // the integrated area: between the baseline and the signal, start to end
132            let steps = 64;
133            let mut tri = Vec::with_capacity(steps + 1);
134            for s in 0..=steps {
135                let t = pe.start_min + (pe.end_min - pe.start_min) * s as f64 / steps as f64;
136                let f = if pe.end_min > pe.start_min {
137                    (t - pe.start_min) / (pe.end_min - pe.start_min)
138                } else {
139                    0.0
140                };
141                let b = pe.baseline_start + (pe.baseline_end - pe.baseline_start) * f;
142                let y = at(t);
143                tri.push((t, b.min(y), b.max(y)));
144            }
145            p.area(fig, &tri, fills[j % 2]);
146        }
147    }
148    let color = theme.series(k);
149    let mut env = openreadout_figure::Envelope::new((p.rect.w * 1.5).max(2.0) as usize, tmin, tmax);
150    for &(t, y) in &pts {
151        env.push(t, y);
152    }
153    p.line_px(
154        fig,
155        env.points(&p),
156        Stroke::new(color, theme.line_width * 0.85),
157    );
158    if let Some(pk) = pk {
159        let num = TextStyle::new(theme.small_size(), theme.ink)
160            .face(Face::Mono)
161            .align(Anchor::Middle, Baseline::Alphabetic)
162            .halo(theme.paper, 2.0);
163        for pe in &pk.peaks {
164            p.line(
165                fig,
166                [
167                    (pe.start_min, pe.baseline_start),
168                    (pe.end_min, pe.baseline_end),
169                ],
170                Stroke::new(theme.accent, theme.hairline()),
171            );
172        }
173        // numbers at the apexes of the peaks big enough to see at this size, tallest first; a
174        // number that would cover another is left out (its peak keeps its baseline and shading)
175        let tallest = pk.peaks.iter().map(|p| p.height).fold(0.0, f64::max);
176        let mut order: Vec<&crate::peaks::Peak> = pk
177            .peaks
178            .iter()
179            .filter(|p| p.height >= tallest * VISIBLE_SHARE)
180            .collect();
181        order.sort_by(|a, b| b.height.total_cmp(&a.height));
182        let mut taken: Vec<openreadout_figure::Rect> = Vec::new();
183        for pe in order {
184            let Some((x, y)) = p.pt(pe.rt_min, at(pe.rt_min)) else {
185                continue;
186            };
187            let ly = (y - fs * 0.6).max(p.rect.y + fs * 0.4);
188            let label = pe.number.to_string();
189            let b = num.bounds(x, ly, &label).inset(-2.0);
190            if taken.iter().any(|t| t.intersects(&b)) {
191                continue;
192            }
193            taken.push(b);
194            fig.stroke(
195                Path::segment(x, y - 2.0, x, y - fs * 0.45),
196                Stroke::new(theme.accent, theme.hairline()),
197            );
198            fig.text(x, ly, &label, &num);
199        }
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn plot_is_deterministic_and_sized() {
209        let rt: Vec<f64> = (0..500).map(|i| f64::from(i) * 0.02).collect();
210        let y: Vec<f64> = rt
211            .iter()
212            .map(|t| 100.0 * (-0.5 * ((t - 5.0) / 0.1f64).powi(2)).exp())
213            .collect();
214        let ch = Chromatogram {
215            label: "test".into(),
216            rt_min: rt.clone(),
217            intensity: y.clone(),
218            ..Chromatogram::default()
219        };
220        let table =
221            crate::peaks::find_peaks(&rt, &y, &crate::peaks::PeakParams::default()).unwrap();
222        let pk = ChromatogramPeaks {
223            peaks: table.peaks,
224            ..ChromatogramPeaks::default()
225        };
226        let a = render(std::slice::from_ref(&ch), &[Some(&pk)], 600).to_raster(1.0);
227        let b = render(std::slice::from_ref(&ch), &[Some(&pk)], 600).to_raster(1.0);
228        assert_eq!(a, b);
229        assert_eq!((a.width, a.height), (600, PANEL_HEIGHT));
230        assert!(!a.is_gray());
231        let empty = render(&[Chromatogram::default()], &[None], 300).to_raster(1.0);
232        assert_eq!(empty.height, PANEL_HEIGHT);
233    }
234}