Skip to main content

lichtung_plot/geometry/
raincloud.rs

1use std::collections::HashMap;
2
3use super::{aligned, dimension, finite};
4use crate::data::source::{collect_source, reserve_source};
5use crate::{plots::RaincloudGeometry, CategoryValues, Error};
6
7const MAX_GROUPS: usize = 512;
8const MAX_DENSITY_PER_GROUP: usize = 2_048;
9const MAX_DENSITY: usize = 1_000_000;
10const MAX_POINTS: usize = 1_000_000;
11
12pub(crate) fn validate_raincloud_counts(
13    groups: usize,
14    density: usize,
15    points: usize,
16) -> Result<(), Error> {
17    if groups == 0 || groups > MAX_GROUPS {
18        return Err(Error::Data(
19            format!("raincloud geometry requires 1..={MAX_GROUPS} summary groups").into(),
20        ));
21    }
22    if density > MAX_DENSITY || points > MAX_POINTS {
23        return Err(Error::Data(
24            "raincloud geometry exceeds its density/raw-point safety limit".into(),
25        ));
26    }
27    Ok(())
28}
29
30#[derive(Debug)]
31pub(crate) struct RaincloudRows {
32    pub(crate) density: Vec<usize>,
33    pub(crate) points: Vec<usize>,
34}
35
36#[derive(Debug)]
37pub(crate) struct RaincloudMembership {
38    pub(crate) range: (f64, f64),
39    pub(crate) groups: Vec<RaincloudRows>,
40}
41
42fn group_key(
43    category: &crate::data::KeyValues,
44    hue: Option<&crate::data::KeyValues>,
45    row: usize,
46) -> Result<(crate::data::RawKey, Option<crate::data::RawKey>), Error> {
47    let key = |values: &crate::data::KeyValues, role| {
48        values
49            .key_at(row)
50            .ok_or_else(|| Error::Data(format!("raincloud {role} is missing at row {row}").into()))
51    };
52    Ok((
53        key(category, "category")?,
54        hue.map(|hue| key(hue, "hue")).transpose()?,
55    ))
56}
57
58fn retain_row(rows: &mut Vec<usize>, row: usize) -> Result<(), Error> {
59    if rows.len() == rows.capacity() {
60        reserve_source(rows, rows.len().max(1))?;
61    }
62    rows.push(row);
63    Ok(())
64}
65
66impl RaincloudGeometry {
67    /// Supply the three independent raincloud geometry domains.
68    #[allow(
69        clippy::too_many_arguments,
70        reason = "each supplied column belongs to one explicit independent domain"
71    )]
72    pub fn new(
73        category_dimension: impl Into<String>,
74        value_dimension: impl Into<String>,
75        category: CategoryValues,
76        q1: crate::NumericValues,
77        median: crate::NumericValues,
78        q3: crate::NumericValues,
79        density_category: CategoryValues,
80        density_y: crate::NumericValues,
81        normalized_width: crate::NumericValues,
82        point_category: CategoryValues,
83        point_y: crate::NumericValues,
84        normalized_strip: crate::NumericValues,
85    ) -> Self {
86        Self {
87            data: std::sync::Arc::new(super::RaincloudData {
88                category_dimension: category_dimension.into(),
89                value_dimension: value_dimension.into(),
90                hue_dimension: None,
91                category,
92                hue: None,
93                q1,
94                median,
95                q3,
96                density_category,
97                density_hue: None,
98                density_y,
99                normalized_width,
100                point_category,
101                point_hue: None,
102                point_y,
103                normalized_strip,
104            }),
105            result: None,
106        }
107    }
108
109    /// Supply the original hue dimension in all three actual domains.
110    #[must_use]
111    pub fn with_hue(
112        mut self,
113        dimension: impl Into<String>,
114        summary: CategoryValues,
115        density: CategoryValues,
116        points: CategoryValues,
117    ) -> Self {
118        let data = std::sync::Arc::make_mut(&mut self.data);
119        data.hue_dimension = Some(dimension.into());
120        data.hue = Some(summary);
121        data.density_hue = Some(density);
122        data.point_hue = Some(points);
123        self.result = None;
124        self
125    }
126
127    /// Original scientific category dimension.
128    pub fn category_dimension(&self) -> &str {
129        &self.data.category_dimension
130    }
131    /// Original scientific value dimension.
132    pub fn value_dimension(&self) -> &str {
133        &self.data.value_dimension
134    }
135    /// Original scientific hue dimension, if present.
136    pub fn hue_dimension(&self) -> Option<&str> {
137        self.data.hue_dimension.as_deref()
138    }
139    /// Original category keys of the category domain.
140    pub fn category(&self) -> crate::data::KeyValues {
141        self.data.category.key_values()
142    }
143    /// Original category keys of the density domain.
144    pub fn density_category(&self) -> crate::data::KeyValues {
145        self.data.density_category.key_values()
146    }
147    /// Original category keys of the point domain.
148    pub fn point_category(&self) -> crate::data::KeyValues {
149        self.data.point_category.key_values()
150    }
151    /// Original hue keys of the hue domain, if supplied.
152    pub fn hue(&self) -> Option<crate::data::KeyValues> {
153        self.data
154            .hue
155            .as_ref()
156            .map(crate::CategoryValues::key_values)
157    }
158    /// Original hue keys of the density domain, if supplied.
159    pub fn density_hue(&self) -> Option<crate::data::KeyValues> {
160        self.data
161            .density_hue
162            .as_ref()
163            .map(crate::CategoryValues::key_values)
164    }
165    /// Original hue keys of the point domain, if supplied.
166    pub fn point_hue(&self) -> Option<crate::data::KeyValues> {
167        self.data
168            .point_hue
169            .as_ref()
170            .map(crate::CategoryValues::key_values)
171    }
172    /// Actual lower quartiles.
173    pub fn q1(&self) -> &crate::NumericValues {
174        &self.data.q1
175    }
176    /// Actual medians.
177    pub fn median(&self) -> &crate::NumericValues {
178        &self.data.median
179    }
180    /// Actual upper quartiles.
181    pub fn q3(&self) -> &crate::NumericValues {
182        &self.data.q3
183    }
184    /// Actual density support.
185    pub fn density_y(&self) -> &crate::NumericValues {
186        &self.data.density_y
187    }
188    /// Actual normalized profile widths.
189    pub fn normalized_width(&self) -> &crate::NumericValues {
190        &self.data.normalized_width
191    }
192    /// Original point values.
193    pub fn point_y(&self) -> &crate::NumericValues {
194        &self.data.point_y
195    }
196    /// Actual normalized strip coordinates.
197    pub fn normalized_strip(&self) -> &crate::NumericValues {
198        &self.data.normalized_strip
199    }
200
201    /// Actual renderer projections of the geometry's category and hue labels.
202    #[doc(hidden)]
203    pub fn label_columns(&self) -> impl Iterator<Item = &CategoryValues> {
204        std::iter::once(&self.data.category).chain(self.data.hue.as_ref())
205    }
206
207    pub(crate) fn membership(&self) -> Result<RaincloudMembership, Error> {
208        self.validate_columns()?;
209        let mut index = HashMap::new();
210        index
211            .try_reserve(self.data.category.len())
212            .map_err(|error| {
213                Error::Render(format!("raincloud group index reservation: {error}").into())
214            })?;
215        let category = self.category();
216        let hue = self.hue();
217        let mut groups = collect_source((0..self.data.category.len()).map(|row| {
218            let key = group_key(&category, hue.as_ref(), row)?;
219            if index.insert(key.clone(), row).is_some() {
220                return Err(Error::Data(
221                    format!("raincloud geometry contains duplicate category-hue identity {key:?}")
222                        .into(),
223                ));
224            }
225            Ok(RaincloudRows {
226                density: Vec::new(),
227                points: Vec::new(),
228            })
229        }))?;
230        let density_category = self.density_category();
231        let density_hue = self.density_hue();
232        let point_category = self.point_category();
233        let point_hue = self.point_hue();
234        for (category, hue, is_density) in [
235            (&density_category, density_hue.as_ref(), true),
236            (&point_category, point_hue.as_ref(), false),
237        ] {
238            for row in 0..category.len() {
239                if row.is_multiple_of(1024) {
240                    crate::operation::checkpoint()?;
241                }
242                crate::operation::work(1)?;
243                let key = group_key(category, hue, row)?;
244                let group = index.get(&key).ok_or_else(|| {
245                    let domain = if is_density { "density" } else { "point" };
246                    Error::Data(
247                        format!(
248                            "raincloud {domain} row {row} names an unknown summary group {key:?}"
249                        )
250                        .into(),
251                    )
252                })?;
253                let members = if is_density {
254                    &mut groups[*group].density
255                } else {
256                    &mut groups[*group].points
257                };
258                retain_row(members, row)?;
259            }
260        }
261        let mut range = (f64::INFINITY, f64::NEG_INFINITY);
262        for (row, group) in groups.iter().enumerate() {
263            let support = self.validate_group(row, group)?;
264            range.0 = range.0.min(support.0);
265            range.1 = range.1.max(support.1);
266        }
267        Ok(RaincloudMembership { range, groups })
268    }
269
270    fn validate_columns(&self) -> Result<(), Error> {
271        dimension(
272            &self.data.category_dimension,
273            "raincloud category dimension",
274        )?;
275        dimension(&self.data.value_dimension, "raincloud value dimension")?;
276        if let Some(hue) = &self.data.hue_dimension {
277            dimension(hue, "raincloud hue dimension")?;
278        }
279        for hue in [&self.data.hue, &self.data.density_hue, &self.data.point_hue] {
280            if hue.is_some() != self.data.hue_dimension.is_some() {
281                return Err(Error::Data("raincloud hue dimension and all three hue columns must be present together or absent together".into()));
282            }
283        }
284        aligned(
285            "raincloud summary",
286            self.data.category.len(),
287            &[
288                ("q1", self.data.q1.len()),
289                ("median", self.data.median.len()),
290                ("q3", self.data.q3.len()),
291            ],
292        )?;
293        aligned(
294            "raincloud density",
295            self.data.density_category.len(),
296            &[
297                ("density_y", self.data.density_y.len()),
298                ("normalized_width", self.data.normalized_width.len()),
299            ],
300        )?;
301        aligned(
302            "raincloud points",
303            self.data.point_category.len(),
304            &[
305                ("point_y", self.data.point_y.len()),
306                ("normalized_strip", self.data.normalized_strip.len()),
307            ],
308        )?;
309        for (domain, len, hue) in [
310            (
311                "raincloud summary",
312                self.data.category.len(),
313                self.data.hue.as_ref(),
314            ),
315            (
316                "raincloud density",
317                self.data.density_category.len(),
318                self.data.density_hue.as_ref(),
319            ),
320            (
321                "raincloud points",
322                self.data.point_category.len(),
323                self.data.point_hue.as_ref(),
324            ),
325        ] {
326            if let Some(hue) = hue {
327                aligned(domain, len, &[(hue.name(), hue.len())])?;
328            }
329        }
330        validate_raincloud_counts(
331            self.data.category.len(),
332            self.data.density_category.len(),
333            self.data.point_category.len(),
334        )
335    }
336
337    fn validate_group(&self, row: usize, group: &RaincloudRows) -> Result<(f64, f64), Error> {
338        if group.density.len() < 2 || group.density.len() > MAX_DENSITY_PER_GROUP {
339            return Err(Error::Data(format!("raincloud geometry group {row} requires 2..={MAX_DENSITY_PER_GROUP} density points").into()));
340        }
341        let mut previous = None;
342        let mut positive = false;
343        for &point in &group.density {
344            let y = finite(&self.data.density_y, point, "raincloud density y")?;
345            let width = finite(
346                &self.data.normalized_width,
347                point,
348                "raincloud density width",
349            )?;
350            if !(0.0..=1.0).contains(&width) {
351                return Err(Error::Data(
352                    format!("raincloud geometry group {row} requires normalized width in [0, 1]")
353                        .into(),
354                ));
355            }
356            if previous.is_some_and(|previous| y <= previous) {
357                return Err(Error::Data(format!("raincloud geometry group {row} density y coordinates must be strictly increasing").into()));
358            }
359            previous = Some(y);
360            positive |= width > 0.0;
361        }
362        if !positive {
363            return Err(Error::Data(
364                format!("raincloud geometry group {row} requires a positive density width").into(),
365            ));
366        }
367        let q1 = finite(&self.data.q1, row, "raincloud q1")?;
368        let median = finite(&self.data.median, row, "raincloud median")?;
369        let q3 = finite(&self.data.q3, row, "raincloud q3")?;
370        let support = (
371            finite(
372                &self.data.density_y,
373                group.density[0],
374                "raincloud density y",
375            )?,
376            finite(
377                &self.data.density_y,
378                group.density[group.density.len() - 1],
379                "raincloud density y",
380            )?,
381        );
382        if q1 > median || median > q3 || q1 < support.0 || q3 > support.1 {
383            return Err(Error::Data(
384                format!(
385                "raincloud geometry group {row} requires q1 <= median <= q3 within density support"
386            )
387                .into(),
388            ));
389        }
390        if group.points.is_empty() {
391            return Err(Error::Data(
392                format!("raincloud geometry group {row} requires at least one raw point").into(),
393            ));
394        }
395        for &point in &group.points {
396            let y = finite(&self.data.point_y, point, "raincloud point y")?;
397            let strip = finite(
398                &self.data.normalized_strip,
399                point,
400                "raincloud normalized strip coordinate",
401            )?;
402            if !(0.0..=1.0).contains(&strip) {
403                return Err(Error::Data(
404                    format!(
405                    "raincloud geometry group {row} requires normalized strip coordinate in [0, 1]"
406                )
407                    .into(),
408                ));
409            }
410            if !(support.0..=support.1).contains(&y) {
411                return Err(Error::Data(
412                    format!(
413                    "raincloud geometry group {row} raw point {point} lies outside density support"
414                )
415                    .into(),
416                ));
417            }
418        }
419        Ok(support)
420    }
421}