lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::collections::HashMap;

use super::{aligned, dimension, finite};
use crate::data::source::{collect_source, reserve_source};
use crate::{plots::RaincloudGeometry, CategoryValues, Error};

const MAX_GROUPS: usize = 512;
const MAX_DENSITY_PER_GROUP: usize = 2_048;
const MAX_DENSITY: usize = 1_000_000;
const MAX_POINTS: usize = 1_000_000;

pub(crate) fn validate_raincloud_counts(
    groups: usize,
    density: usize,
    points: usize,
) -> Result<(), Error> {
    if groups == 0 || groups > MAX_GROUPS {
        return Err(Error::Data(
            format!("raincloud geometry requires 1..={MAX_GROUPS} summary groups").into(),
        ));
    }
    if density > MAX_DENSITY || points > MAX_POINTS {
        return Err(Error::Data(
            "raincloud geometry exceeds its density/raw-point safety limit".into(),
        ));
    }
    Ok(())
}

#[derive(Debug)]
pub(crate) struct RaincloudRows {
    pub(crate) density: Vec<usize>,
    pub(crate) points: Vec<usize>,
}

#[derive(Debug)]
pub(crate) struct RaincloudMembership {
    pub(crate) range: (f64, f64),
    pub(crate) groups: Vec<RaincloudRows>,
}

fn group_key(
    category: &crate::data::KeyValues,
    hue: Option<&crate::data::KeyValues>,
    row: usize,
) -> Result<(crate::data::RawKey, Option<crate::data::RawKey>), Error> {
    let key = |values: &crate::data::KeyValues, role| {
        values
            .key_at(row)
            .ok_or_else(|| Error::Data(format!("raincloud {role} is missing at row {row}").into()))
    };
    Ok((
        key(category, "category")?,
        hue.map(|hue| key(hue, "hue")).transpose()?,
    ))
}

fn retain_row(rows: &mut Vec<usize>, row: usize) -> Result<(), Error> {
    if rows.len() == rows.capacity() {
        reserve_source(rows, rows.len().max(1))?;
    }
    rows.push(row);
    Ok(())
}

impl RaincloudGeometry {
    /// Supply the three independent raincloud geometry domains.
    #[allow(
        clippy::too_many_arguments,
        reason = "each supplied column belongs to one explicit independent domain"
    )]
    pub fn new(
        category_dimension: impl Into<String>,
        value_dimension: impl Into<String>,
        category: CategoryValues,
        q1: crate::NumericValues,
        median: crate::NumericValues,
        q3: crate::NumericValues,
        density_category: CategoryValues,
        density_y: crate::NumericValues,
        normalized_width: crate::NumericValues,
        point_category: CategoryValues,
        point_y: crate::NumericValues,
        normalized_strip: crate::NumericValues,
    ) -> Self {
        Self {
            data: std::sync::Arc::new(super::RaincloudData {
                category_dimension: category_dimension.into(),
                value_dimension: value_dimension.into(),
                hue_dimension: None,
                category,
                hue: None,
                q1,
                median,
                q3,
                density_category,
                density_hue: None,
                density_y,
                normalized_width,
                point_category,
                point_hue: None,
                point_y,
                normalized_strip,
            }),
            result: None,
        }
    }

    /// Supply the original hue dimension in all three actual domains.
    #[must_use]
    pub fn with_hue(
        mut self,
        dimension: impl Into<String>,
        summary: CategoryValues,
        density: CategoryValues,
        points: CategoryValues,
    ) -> Self {
        let data = std::sync::Arc::make_mut(&mut self.data);
        data.hue_dimension = Some(dimension.into());
        data.hue = Some(summary);
        data.density_hue = Some(density);
        data.point_hue = Some(points);
        self.result = None;
        self
    }

    /// Original scientific category dimension.
    pub fn category_dimension(&self) -> &str {
        &self.data.category_dimension
    }
    /// Original scientific value dimension.
    pub fn value_dimension(&self) -> &str {
        &self.data.value_dimension
    }
    /// Original scientific hue dimension, if present.
    pub fn hue_dimension(&self) -> Option<&str> {
        self.data.hue_dimension.as_deref()
    }
    /// Original category keys of the category domain.
    pub fn category(&self) -> crate::data::KeyValues {
        self.data.category.key_values()
    }
    /// Original category keys of the density domain.
    pub fn density_category(&self) -> crate::data::KeyValues {
        self.data.density_category.key_values()
    }
    /// Original category keys of the point domain.
    pub fn point_category(&self) -> crate::data::KeyValues {
        self.data.point_category.key_values()
    }
    /// Original hue keys of the hue domain, if supplied.
    pub fn hue(&self) -> Option<crate::data::KeyValues> {
        self.data
            .hue
            .as_ref()
            .map(crate::CategoryValues::key_values)
    }
    /// Original hue keys of the density domain, if supplied.
    pub fn density_hue(&self) -> Option<crate::data::KeyValues> {
        self.data
            .density_hue
            .as_ref()
            .map(crate::CategoryValues::key_values)
    }
    /// Original hue keys of the point domain, if supplied.
    pub fn point_hue(&self) -> Option<crate::data::KeyValues> {
        self.data
            .point_hue
            .as_ref()
            .map(crate::CategoryValues::key_values)
    }
    /// Actual lower quartiles.
    pub fn q1(&self) -> &crate::NumericValues {
        &self.data.q1
    }
    /// Actual medians.
    pub fn median(&self) -> &crate::NumericValues {
        &self.data.median
    }
    /// Actual upper quartiles.
    pub fn q3(&self) -> &crate::NumericValues {
        &self.data.q3
    }
    /// Actual density support.
    pub fn density_y(&self) -> &crate::NumericValues {
        &self.data.density_y
    }
    /// Actual normalized profile widths.
    pub fn normalized_width(&self) -> &crate::NumericValues {
        &self.data.normalized_width
    }
    /// Original point values.
    pub fn point_y(&self) -> &crate::NumericValues {
        &self.data.point_y
    }
    /// Actual normalized strip coordinates.
    pub fn normalized_strip(&self) -> &crate::NumericValues {
        &self.data.normalized_strip
    }

    /// Actual renderer projections of the geometry's category and hue labels.
    #[doc(hidden)]
    pub fn label_columns(&self) -> impl Iterator<Item = &CategoryValues> {
        std::iter::once(&self.data.category).chain(self.data.hue.as_ref())
    }

    pub(crate) fn membership(&self) -> Result<RaincloudMembership, Error> {
        self.validate_columns()?;
        let mut index = HashMap::new();
        index
            .try_reserve(self.data.category.len())
            .map_err(|error| {
                Error::Render(format!("raincloud group index reservation: {error}").into())
            })?;
        let category = self.category();
        let hue = self.hue();
        let mut groups = collect_source((0..self.data.category.len()).map(|row| {
            let key = group_key(&category, hue.as_ref(), row)?;
            if index.insert(key.clone(), row).is_some() {
                return Err(Error::Data(
                    format!("raincloud geometry contains duplicate category-hue identity {key:?}")
                        .into(),
                ));
            }
            Ok(RaincloudRows {
                density: Vec::new(),
                points: Vec::new(),
            })
        }))?;
        let density_category = self.density_category();
        let density_hue = self.density_hue();
        let point_category = self.point_category();
        let point_hue = self.point_hue();
        for (category, hue, is_density) in [
            (&density_category, density_hue.as_ref(), true),
            (&point_category, point_hue.as_ref(), false),
        ] {
            for row in 0..category.len() {
                if row.is_multiple_of(1024) {
                    crate::operation::checkpoint()?;
                }
                crate::operation::check()?;
                let key = group_key(category, hue, row)?;
                let group = index.get(&key).ok_or_else(|| {
                    let domain = if is_density { "density" } else { "point" };
                    Error::Data(
                        format!(
                            "raincloud {domain} row {row} names an unknown summary group {key:?}"
                        )
                        .into(),
                    )
                })?;
                let members = if is_density {
                    &mut groups[*group].density
                } else {
                    &mut groups[*group].points
                };
                retain_row(members, row)?;
            }
        }
        let mut range = (f64::INFINITY, f64::NEG_INFINITY);
        for (row, group) in groups.iter().enumerate() {
            let support = self.validate_group(row, group)?;
            range.0 = range.0.min(support.0);
            range.1 = range.1.max(support.1);
        }
        Ok(RaincloudMembership { range, groups })
    }

    fn validate_columns(&self) -> Result<(), Error> {
        dimension(
            &self.data.category_dimension,
            "raincloud category dimension",
        )?;
        dimension(&self.data.value_dimension, "raincloud value dimension")?;
        if let Some(hue) = &self.data.hue_dimension {
            dimension(hue, "raincloud hue dimension")?;
        }
        for hue in [&self.data.hue, &self.data.density_hue, &self.data.point_hue] {
            if hue.is_some() != self.data.hue_dimension.is_some() {
                return Err(Error::Data("raincloud hue dimension and all three hue columns must be present together or absent together".into()));
            }
        }
        aligned(
            "raincloud summary",
            self.data.category.len(),
            &[
                ("q1", self.data.q1.len()),
                ("median", self.data.median.len()),
                ("q3", self.data.q3.len()),
            ],
        )?;
        aligned(
            "raincloud density",
            self.data.density_category.len(),
            &[
                ("density_y", self.data.density_y.len()),
                ("normalized_width", self.data.normalized_width.len()),
            ],
        )?;
        aligned(
            "raincloud points",
            self.data.point_category.len(),
            &[
                ("point_y", self.data.point_y.len()),
                ("normalized_strip", self.data.normalized_strip.len()),
            ],
        )?;
        for (domain, len, hue) in [
            (
                "raincloud summary",
                self.data.category.len(),
                self.data.hue.as_ref(),
            ),
            (
                "raincloud density",
                self.data.density_category.len(),
                self.data.density_hue.as_ref(),
            ),
            (
                "raincloud points",
                self.data.point_category.len(),
                self.data.point_hue.as_ref(),
            ),
        ] {
            if let Some(hue) = hue {
                aligned(domain, len, &[(hue.name(), hue.len())])?;
            }
        }
        validate_raincloud_counts(
            self.data.category.len(),
            self.data.density_category.len(),
            self.data.point_category.len(),
        )
    }

    fn validate_group(&self, row: usize, group: &RaincloudRows) -> Result<(f64, f64), Error> {
        if group.density.len() < 2 || group.density.len() > MAX_DENSITY_PER_GROUP {
            return Err(Error::Data(format!("raincloud geometry group {row} requires 2..={MAX_DENSITY_PER_GROUP} density points").into()));
        }
        let mut previous = None;
        let mut positive = false;
        for &point in &group.density {
            let y = finite(&self.data.density_y, point, "raincloud density y")?;
            let width = finite(
                &self.data.normalized_width,
                point,
                "raincloud density width",
            )?;
            if !(0.0..=1.0).contains(&width) {
                return Err(Error::Data(
                    format!("raincloud geometry group {row} requires normalized width in [0, 1]")
                        .into(),
                ));
            }
            if previous.is_some_and(|previous| y <= previous) {
                return Err(Error::Data(format!("raincloud geometry group {row} density y coordinates must be strictly increasing").into()));
            }
            previous = Some(y);
            positive |= width > 0.0;
        }
        if !positive {
            return Err(Error::Data(
                format!("raincloud geometry group {row} requires a positive density width").into(),
            ));
        }
        let q1 = finite(&self.data.q1, row, "raincloud q1")?;
        let median = finite(&self.data.median, row, "raincloud median")?;
        let q3 = finite(&self.data.q3, row, "raincloud q3")?;
        let support = (
            finite(
                &self.data.density_y,
                group.density[0],
                "raincloud density y",
            )?,
            finite(
                &self.data.density_y,
                group.density[group.density.len() - 1],
                "raincloud density y",
            )?,
        );
        if q1 > median || median > q3 || q1 < support.0 || q3 > support.1 {
            return Err(Error::Data(
                format!(
                "raincloud geometry group {row} requires q1 <= median <= q3 within density support"
            )
                .into(),
            ));
        }
        if group.points.is_empty() {
            return Err(Error::Data(
                format!("raincloud geometry group {row} requires at least one raw point").into(),
            ));
        }
        for &point in &group.points {
            let y = finite(&self.data.point_y, point, "raincloud point y")?;
            let strip = finite(
                &self.data.normalized_strip,
                point,
                "raincloud normalized strip coordinate",
            )?;
            if !(0.0..=1.0).contains(&strip) {
                return Err(Error::Data(
                    format!(
                    "raincloud geometry group {row} requires normalized strip coordinate in [0, 1]"
                )
                    .into(),
                ));
            }
            if !(support.0..=support.1).contains(&y) {
                return Err(Error::Data(
                    format!(
                    "raincloud geometry group {row} raw point {point} lies outside density support"
                )
                    .into(),
                ));
            }
        }
        Ok(support)
    }
}