Skip to main content

xpict_core/
plotdot.rs

1//! Concentric plot-dot shading (xenopict `PlotDot` semantics).
2//!
3//! Python host draw stack removed; this module is SoT.
4
5/// One disk before paint: radius fraction in `[0, 1]`, color stop in `[-1, 1]`.
6#[derive(Debug, Clone, Copy, PartialEq)]
7pub struct ShadeDisk {
8    pub radius_frac: f64,
9    pub color_z: f64,
10    pub x: f64,
11    pub y: f64,
12}
13
14/// Map `z ∈ [-1, 1]` to concentric `(radius_frac, color_z)` rings.
15///
16/// Rings sort weak → strong so intense colors paint on top — same order as
17/// xenopict / Python `PlotDot`.
18#[derive(Debug, Clone)]
19pub struct PlotDot {
20    levels: usize,
21    stops: Vec<f64>,
22}
23
24impl Default for PlotDot {
25    fn default() -> Self {
26        Self::new(4)
27    }
28}
29
30impl PlotDot {
31    pub fn new(levels: usize) -> Self {
32        let levels = levels.max(1);
33        let stops = (0..levels)
34            .map(|i| (i + 1) as f64 / levels as f64)
35            .collect();
36        Self { levels, stops }
37    }
38
39    fn radius(&self, z: f64, level: usize) -> f64 {
40        let az = z.abs();
41        if level == 0 {
42            return self.stops[0].sqrt();
43        }
44        let offset = 1.0 - self.stops[level];
45        let r = az - offset;
46        if r < self.stops[0] {
47            0.0
48        } else {
49            r.sqrt()
50        }
51    }
52
53    fn color(&self, z: f64, level: usize) -> f64 {
54        let sign = if z < 0.0 { -1.0 } else { 1.0 };
55        if level == 0 {
56            z
57        } else {
58            sign * self.stops[self.stops.len() - level - 1]
59        }
60    }
61
62    /// Rings for one score; empty when `|z| < 0.05`.
63    pub fn rings(&self, z: f64) -> Vec<(f64, f64)> {
64        if z.abs() < 0.05 {
65            return Vec::new();
66        }
67        (0..self.levels)
68            .map(|lvl| (self.radius(z, lvl), self.color(z, lvl)))
69            .filter(|(r, _)| *r > 0.0)
70            .collect()
71    }
72
73    /// All disks for a molecule, sorted weak/small first.
74    pub fn disks(&self, zs: &[f64], coords: &[(f64, f64)]) -> Vec<ShadeDisk> {
75        let mut dots = Vec::new();
76        for (z, &(x, y)) in zs.iter().zip(coords.iter()) {
77            for (radius_frac, color_z) in self.rings(*z) {
78                dots.push(ShadeDisk {
79                    radius_frac,
80                    color_z,
81                    x,
82                    y,
83                });
84            }
85        }
86        dots.sort_by(|a, b| {
87            a.color_z
88                .abs()
89                .partial_cmp(&b.color_z.abs())
90                .unwrap_or(std::cmp::Ordering::Equal)
91                .then_with(|| {
92                    a.radius_frac
93                        .partial_cmp(&b.radius_frac)
94                        .unwrap_or(std::cmp::Ordering::Equal)
95                })
96        });
97        dots
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn skips_near_zero_scores() {
107        let dots =
108            PlotDot::default().disks(&[0.0, 0.01, 0.9], &[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)]);
109        assert!(dots.iter().all(|d| d.color_z.abs() >= 0.05));
110        assert!(dots.iter().any(|d| d.color_z.abs() > 0.5));
111    }
112
113    #[test]
114    fn full_score_has_four_rings() {
115        let rings = PlotDot::default().rings(1.0);
116        assert_eq!(rings.len(), 4);
117        assert!((rings[0].0 - 0.5).abs() < 1e-9);
118        assert!((rings[0].1 - 1.0).abs() < 1e-9);
119    }
120
121    /// Parity with Python ``test_plotdot_rings_match_python`` sample scores.
122    #[test]
123    fn plotdot_rings_sample_scores() {
124        let pd = PlotDot::default();
125        for z in [0.25, 0.5, 0.9, 1.0] {
126            let rings = pd.rings(z);
127            assert!(!rings.is_empty() || z < 0.05);
128            for &(r, c) in &rings {
129                assert!(r > 0.0 && r <= 1.0);
130                assert!(c.abs() <= 1.0 + 1e-9);
131            }
132        }
133    }
134}