Skip to main content

openreadout_quant/
plot.rs

1//! PNG/JPEG plots of chromatograms, optionally with their integrated peaks shaded, baselines
2//! drawn and peaks numbered: the picture a chromatographer checks an integration against.
3//! Deterministic: the same input gives the same bytes.
4
5use openreadout_preview::Canvas;
6use openreadout_preview::color::TRACE_PALETTE;
7
8use crate::analyze::ChromatogramPeaks;
9use crate::extract::Chromatogram;
10
11const BG: [u8; 3] = [255, 255, 255];
12const AXIS: [u8; 3] = [90, 90, 90];
13const TEXT: [u8; 3] = [40, 40, 40];
14const BASE: [u8; 3] = [200, 30, 30];
15const FILLS: [[u8; 3]; 2] = [[190, 215, 245], [250, 215, 170]];
16const LEFT: i64 = 64;
17const RIGHT: i64 = 14;
18const TOP: i64 = 22;
19const BOTTOM: i64 = 24;
20/// Height of one chromatogram panel, pixels.
21pub const PANEL_HEIGHT: u32 = 240;
22
23fn nice_step(span: f64, ticks: f64) -> f64 {
24    if !(span.is_finite() && span > 0.0) {
25        return 1.0;
26    }
27    let raw = span / ticks;
28    let p = 10f64.powf(raw.log10().floor());
29    let m = raw / p;
30    let k = if m < 1.5 {
31        1.0
32    } else if m < 3.5 {
33        2.0
34    } else if m < 7.5 {
35        5.0
36    } else {
37        10.0
38    };
39    k * p
40}
41
42fn label(v: f64) -> String {
43    if v != 0.0 && (v.abs() >= 1e5 || v.abs() < 1e-2) {
44        let e = v.abs().log10().floor() as i32;
45        format!("{:.2}E{e}", v / 10f64.powi(e))
46    } else {
47        let s = format!("{v:.3}");
48        s.trim_end_matches('0').trim_end_matches('.').to_string()
49    }
50}
51
52/// Draw the chromatograms, one panel each, `width` pixels wide. `peaks[k]`, when present, is
53/// drawn over panel `k`.
54pub fn render(chroms: &[Chromatogram], peaks: &[Option<&ChromatogramPeaks>], width: u32) -> Canvas {
55    render_labelled(chroms, peaks, &[], width)
56}
57
58/// [`render`] with an x-axis label per panel (`x_labels[k]`; `MIN` where none is given), for
59/// spectra drawn the same way.
60pub fn render_labelled(
61    chroms: &[Chromatogram],
62    peaks: &[Option<&ChromatogramPeaks>],
63    x_labels: &[String],
64    width: u32,
65) -> Canvas {
66    let width = width.clamp(200, 8192);
67    let n = chroms.len().max(1) as u32;
68    let mut c = Canvas::new(width, PANEL_HEIGHT * n, BG);
69    for (k, ch) in chroms.iter().enumerate() {
70        let top = i64::from(PANEL_HEIGHT) * k as i64;
71        let label = x_labels.get(k).map_or("MIN", String::as_str);
72        panel(&mut c, ch, peaks.get(k).copied().flatten(), top, k, label);
73    }
74    c
75}
76
77fn panel(
78    c: &mut Canvas,
79    ch: &Chromatogram,
80    pk: Option<&ChromatogramPeaks>,
81    top: i64,
82    k: usize,
83    x_label: &str,
84) {
85    let w = i64::from(c.width);
86    let (x0, x1) = (LEFT, w - RIGHT);
87    let (y0, y1) = (top + TOP, top + i64::from(PANEL_HEIGHT) - BOTTOM);
88    let title = format!(
89        "{}{}",
90        ch.label,
91        ch.intensity_unit
92            .as_deref()
93            .map(|u| format!(" ({u})"))
94            .unwrap_or_default()
95    );
96    c.text(x0, top + 6, 2, TEXT, &title);
97    c.line(x0, y1, x1, y1, AXIS);
98    c.line(x0, y0, x0, y1, AXIS);
99    let pts: Vec<(f64, f64)> = ch
100        .rt_min
101        .iter()
102        .zip(&ch.intensity)
103        .filter(|(t, y)| t.is_finite() && y.is_finite())
104        .map(|(t, y)| (*t, *y))
105        .collect();
106    if pts.len() < 2 {
107        c.text(x0 + 8, i64::midpoint(y0, y1), 2, TEXT, "NO DATA");
108        return;
109    }
110    let (tmin, tmax) = (pts[0].0, pts[pts.len() - 1].0);
111    let ymax = pts.iter().fold(f64::NEG_INFINITY, |m, p| m.max(p.1));
112    let ymin = pts.iter().fold(0.0f64, |m, p| m.min(p.1));
113    let yspan = if ymax > ymin {
114        (ymax - ymin) * 1.08
115    } else {
116        1.0
117    };
118    let tspan = if tmax > tmin { tmax - tmin } else { 1.0 };
119    let px = |t: f64| x0 + ((t - tmin) / tspan * (x1 - x0) as f64).round() as i64;
120    let py = |y: f64| y1 - ((y - ymin) / yspan * (y1 - y0) as f64).round() as i64;
121    // signal value at time t (linear interpolation)
122    let at = |t: f64| -> f64 {
123        let i = pts.partition_point(|p| p.0 < t);
124        if i == 0 {
125            return pts[0].1;
126        }
127        if i >= pts.len() {
128            return pts[pts.len() - 1].1;
129        }
130        let (a, b) = (pts[i - 1], pts[i]);
131        if b.0 == a.0 {
132            b.1
133        } else {
134            a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0)
135        }
136    };
137    if let Some(pk) = pk {
138        for (j, p) in pk.peaks.iter().enumerate() {
139            let fill = FILLS[j % 2];
140            let (xa, xb) = (px(p.start_min), px(p.end_min));
141            for x in xa..=xb {
142                let t = tmin + (x - x0) as f64 / (x1 - x0) as f64 * tspan;
143                let f = if p.end_min > p.start_min {
144                    (t - p.start_min) / (p.end_min - p.start_min)
145                } else {
146                    0.0
147                };
148                let b = p.baseline_start + (p.baseline_end - p.baseline_start) * f;
149                let (ya, yb) = (py(b), py(at(t)));
150                c.line(x, ya.min(yb), x, ya.max(yb), fill);
151            }
152        }
153    }
154    let color = TRACE_PALETTE[k % TRACE_PALETTE.len()];
155    let mut prev: Option<(i64, i64)> = None;
156    for &(t, y) in &pts {
157        let q = (px(t), py(y));
158        if let Some(p) = prev
159            && p != q
160        {
161            c.line(p.0, p.1, q.0, q.1, color);
162        }
163        prev = Some(q);
164    }
165    if let Some(pk) = pk {
166        for p in &pk.peaks {
167            c.line(
168                px(p.start_min),
169                py(p.baseline_start),
170                px(p.end_min),
171                py(p.baseline_end),
172                BASE,
173            );
174            let (xa, ya) = (px(p.rt_min), py(at(p.rt_min)));
175            let s = p.number.to_string();
176            c.text(
177                xa - openreadout_preview::canvas::text_width(&s, 1) / 2,
178                (ya - 8).max(y0 - 2),
179                1,
180                TEXT,
181                &s,
182            );
183        }
184    }
185    // axes: time ticks, intensity range
186    let step = nice_step(tspan, 8.0);
187    let mut t = (tmin / step).ceil() * step;
188    while t <= tmax + 1e-9 {
189        let x = px(t);
190        c.line(x, y1, x, y1 + 3, AXIS);
191        let s = label(t);
192        c.text(
193            x - openreadout_preview::canvas::text_width(&s, 1) / 2,
194            y1 + 6,
195            1,
196            TEXT,
197            &s,
198        );
199        t += step;
200    }
201    let s = x_label;
202    c.text(
203        x1 - openreadout_preview::canvas::text_width(s, 1),
204        y1 + 14,
205        1,
206        TEXT,
207        s,
208    );
209    for v in [ymin, ymin + (ymax - ymin) / 2.0, ymax] {
210        let y = py(v);
211        c.line(x0 - 3, y, x0, y, AXIS);
212        let s = label(v);
213        c.text(
214            x0 - 6 - openreadout_preview::canvas::text_width(&s, 1),
215            y - 2,
216            1,
217            TEXT,
218            &s,
219        );
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn plot_is_deterministic_and_sized() {
229        let rt: Vec<f64> = (0..500).map(|i| f64::from(i) * 0.02).collect();
230        let y: Vec<f64> = rt
231            .iter()
232            .map(|t| 100.0 * (-0.5 * ((t - 5.0) / 0.1f64).powi(2)).exp())
233            .collect();
234        let ch = Chromatogram {
235            label: "test".into(),
236            rt_min: rt.clone(),
237            intensity: y.clone(),
238            ..Chromatogram::default()
239        };
240        let table =
241            crate::peaks::find_peaks(&rt, &y, &crate::peaks::PeakParams::default()).unwrap();
242        let pk = ChromatogramPeaks {
243            peaks: table.peaks,
244            ..ChromatogramPeaks::default()
245        };
246        let a = render(std::slice::from_ref(&ch), &[Some(&pk)], 600);
247        let b = render(std::slice::from_ref(&ch), &[Some(&pk)], 600);
248        assert_eq!(a, b);
249        assert_eq!((a.width, a.height), (600, PANEL_HEIGHT));
250        assert!(!a.is_gray());
251        let empty = render(&[Chromatogram::default()], &[None], 300);
252        assert_eq!(empty.height, PANEL_HEIGHT);
253        assert_eq!(nice_step(10.0, 8.0), 1.0);
254        assert_eq!(label(1_500_000.0), "1.50E6");
255    }
256}