Skip to main content

lichtung_plot/plots/violin/
result.rs

1//! Actual probability density and separate display widths of each prepared group.
2
3use std::sync::Arc;
4
5use crate::{
6    builder::PlotDescription,
7    data::{
8        Bounds, DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload, ExactInteger,
9        GroupKeys, GroupedObservations, IntegerValues, MemberAddress, PlotData, SourceMembers,
10    },
11    elements::ElementRef,
12    plots::categorical_distribution::result::{
13        group_members, group_slots, keys_for_slots, observations, sample_value, BoxColumns,
14        BoxSummary,
15    },
16    stats::results::{numeric_column, ResultDomains},
17    NumericValues, Result,
18};
19
20/// Exact sample counts in the actual group domain of a density profile.
21#[derive(Debug, Clone)]
22pub struct ProfileCounts(Arc<CountsData>);
23
24#[derive(Debug)]
25struct CountsData {
26    groups: GroupKeys,
27    counts: IntegerValues,
28    domains: ResultDomains,
29}
30
31impl ProfileCounts {
32    /// Original grouping keys, one per count.
33    pub fn groups(&self) -> &GroupKeys {
34        &self.0.groups
35    }
36    /// Observations admitted to density estimation, not the number of evaluated nodes.
37    pub fn counts(&self) -> &IntegerValues {
38        &self.0.counts
39    }
40    /// The actual group count domain.
41    pub fn domains(&self) -> &[DataDomainInfo] {
42        self.0.domains.infos()
43    }
44    /// Original group membership.
45    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
46        self.0.domains.members(&address.into())
47    }
48    /// Original group membership in the specified domain.
49    pub fn members_in(
50        &self,
51        domain: &DataDomainRef,
52        address: impl Into<MemberAddress>,
53    ) -> Result<Option<SourceMembers>> {
54        self.0.domains.members_in(domain, &address.into())
55    }
56
57    fn from_result(
58        owner: &ElementRef,
59        groups: GroupKeys,
60        counts: IntegerValues,
61        members: Vec<Option<SourceMembers>>,
62    ) -> Result<Self> {
63        let mut components = groups.components()?;
64        crate::data::source::reserve_source(&mut components, 1)?;
65        components.push(DataComponentInfo::scientific(
66            "counts",
67            &DataPayload::Integer(counts.clone()),
68        )?);
69        let info = DataDomainInfo::bound(
70            DataDomainRef::scientific(owner, None),
71            groups.len(),
72            None,
73            components,
74        )
75        .with_keys(&groups.member_keys()?);
76        let mut domains = ResultDomains::default();
77        domains.push_info(info, members)?;
78        Ok(Self(crate::data::source::source_arc(CountsData {
79            groups,
80            counts,
81            domains,
82        })?))
83    }
84}
85
86/// Evaluated scientific density profiles and the independent real observations
87/// and summaries used by the categorical distribution renderer.
88#[derive(Debug, Clone)]
89pub struct DensityProfiles(Arc<ProfileData>);
90
91#[derive(Debug)]
92struct ProfileData {
93    groups: GroupKeys,
94    coordinate: NumericValues,
95    density: NumericValues,
96    normalized_width: NumericValues,
97    bandwidth: NumericValues,
98    display_maximum: NumericValues,
99    summaries: BoxSummary,
100    observations: GroupedObservations,
101    counts: ProfileCounts,
102    domains: ResultDomains,
103}
104
105impl DensityProfiles {
106    pub(crate) fn result_domains(&self) -> &ResultDomains {
107        &self.0.domains
108    }
109
110    /// Actual group key per ordered curve node.
111    pub fn groups(&self) -> &GroupKeys {
112        &self.0.groups
113    }
114    /// Evaluation coordinates.
115    pub fn coordinate(&self) -> &NumericValues {
116        &self.0.coordinate
117    }
118    /// Original KDE values before any display normalization or closure.
119    pub fn density(&self) -> &NumericValues {
120        &self.0.density
121    }
122    /// Dimensionless painted profile widths, including the actual closing seam.
123    pub fn normalized_width(&self) -> &NumericValues {
124        &self.0.normalized_width
125    }
126    /// Actual kernel bandwidth at each node of its group.
127    pub fn bandwidth(&self) -> &NumericValues {
128        &self.0.bandwidth
129    }
130    /// Actual per-group divisor used for display normalization.
131    pub fn display_maximum(&self) -> &NumericValues {
132        &self.0.display_maximum
133    }
134    /// Actual inner box statistics.
135    pub fn get_summaries(&self) -> Option<&BoxSummary> {
136        Some(&self.0.summaries)
137    }
138    /// Actual admitted observations in their independent domain.
139    pub fn get_observations(&self) -> Option<&GroupedObservations> {
140        Some(&self.0.observations)
141    }
142    /// Actual group counts.
143    pub fn get_counts(&self) -> Option<&ProfileCounts> {
144        Some(&self.0.counts)
145    }
146    /// Actual curve, summary, observation and count domains.
147    pub fn domains(&self) -> &[DataDomainInfo] {
148        self.0.domains.infos()
149    }
150    /// Read a member in a specified domain.
151    pub fn members_in(
152        &self,
153        domain: &DataDomainRef,
154        address: impl Into<MemberAddress>,
155    ) -> Result<Option<SourceMembers>> {
156        self.0.domains.members_in(domain, &address.into())
157    }
158    /// Read a member when there is one actual domain.
159    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
160        self.0.domains.members(&address.into())
161    }
162}
163
164impl super::PreparedViolin {
165    fn summaries(
166        &self,
167        owner: &ElementRef,
168        groups: GroupKeys,
169        members: Vec<Option<SourceMembers>>,
170    ) -> Result<BoxSummary> {
171        let fields = BoxColumns {
172            q1: numeric_column("q1", self.densities.iter().map(|d| d.summary.q1))?,
173            median: numeric_column("median", self.densities.iter().map(|d| d.summary.median))?,
174            q3: numeric_column("q3", self.densities.iter().map(|d| d.summary.q3))?,
175            low: numeric_column("low", self.densities.iter().map(|d| d.summary.lo_whisker))?,
176            high: numeric_column("high", self.densities.iter().map(|d| d.summary.hi_whisker))?,
177            fences: Some(Bounds::new(
178                numeric_column(
179                    "lower_fence",
180                    self.densities.iter().map(|d| d.summary.lo_fence),
181                )?,
182                numeric_column(
183                    "upper_fence",
184                    self.densities.iter().map(|d| d.summary.hi_fence),
185                )?,
186            )),
187        };
188        // Violin computes whiskers but does not select a separate outlier population.
189        BoxSummary::from_result(owner, groups, fields, members, None)
190    }
191
192    pub(crate) fn scientific_result(
193        &self,
194        chart: &PlotDescription,
195        owner: &ElementRef,
196    ) -> Result<DensityProfiles> {
197        let sample = &self.sample;
198        let input = sample_value(chart, owner)?;
199        let slots = group_slots(sample)?;
200        let group_keys = keys_for_slots(chart, &slots)?;
201        let members = group_members(sample, &input)?;
202        let summaries = self.summaries(owner, group_keys.clone(), members.clone())?;
203        let counts = ProfileCounts::from_result(
204            owner,
205            group_keys,
206            IntegerValues::new(
207                "count",
208                sample
209                    .groups
210                    .iter()
211                    .map(|group| ExactInteger::from(group.observations.len())),
212            )?,
213            members.clone(),
214        )?;
215        let n = self.grid.len();
216        let nodes = crate::data::source::collect_source(
217            slots
218                .into_iter()
219                .flat_map(|slot| std::iter::repeat_n(slot, n).map(Ok)),
220        )?;
221        let groups = keys_for_slots(chart, &nodes)?;
222        let coordinate = numeric_column(
223            input.info().name().unwrap_or("value"),
224            self.densities
225                .iter()
226                .flat_map(|_| self.grid.iter().copied()),
227        )?;
228        let density = numeric_column(
229            "density",
230            self.densities
231                .iter()
232                .flat_map(|d| d.densities.iter().copied()),
233        )?;
234        let normalized_width = numeric_column(
235            "normalized_width",
236            self.densities
237                .iter()
238                .flat_map(|d| d.display_values().map(|v| v / d.maximum)),
239        )?;
240        let bandwidth = numeric_column(
241            "bandwidth",
242            self.densities
243                .iter()
244                .flat_map(|d| std::iter::repeat_n(d.bandwidth, n)),
245        )?;
246        let display_maximum = numeric_column(
247            "display_maximum",
248            self.densities
249                .iter()
250                .flat_map(|d| std::iter::repeat_n(d.maximum, n)),
251        )?;
252        let observations = observations(
253            chart,
254            owner,
255            &input,
256            sample.groups.iter().flat_map(|group| &group.observations),
257        )?;
258
259        let mut components = groups.components()?;
260        crate::data::source::reserve_source(&mut components, 5)?;
261        for (name, values) in [
262            ("coordinate", &coordinate),
263            ("density", &density),
264            ("normalized_width", &normalized_width),
265            ("bandwidth", &bandwidth),
266            ("display_maximum", &display_maximum),
267        ] {
268            components.push(DataComponentInfo::scientific(
269                name,
270                &DataPayload::Numeric(values.clone()),
271            )?);
272        }
273        // Every node of one estimated curve depends on the same admitted group.
274        let node_members = crate::data::source::collect_source(
275            members
276                .into_iter()
277                .flat_map(|group| std::iter::repeat_n(group, n).map(Ok)),
278        )?;
279        let mut domains = ResultDomains::default();
280        domains.push(owner, None, components, node_members)?;
281        domains.extend(summaries.result_domains())?;
282        domains.extend(observations.result_domains())?;
283        domains.extend(&counts.0.domains)?;
284        Ok(DensityProfiles(crate::data::source::source_arc(
285            ProfileData {
286                groups,
287                coordinate,
288                density,
289                normalized_width,
290                bandwidth,
291                display_maximum,
292                summaries,
293                observations,
294                counts,
295                domains,
296            },
297        )?))
298    }
299}
300
301fn prepare_result(
302    chart: &PlotDescription,
303    data: PlotData<'_, '_>,
304    owner: &ElementRef,
305) -> Result<DensityProfiles> {
306    super::prepare(chart, data, None)?
307        .0
308        .scientific_result(chart, owner)
309}
310
311crate::orchestrator::science::stat_result_api!(Violin, DensityProfiles, |source, data, layer| {
312    prepare_result(source, data, layer)
313});
314
315#[cfg(test)]
316#[test]
317fn result_capture_does_not_reestimate_violin_groups() {
318    use crate::stats::distribution::KDE_CALLS;
319    let plot = crate::Plot::violin(
320        crate::CategoryValues::new("category", ["A", "A", "B", "B"]).unwrap(),
321        NumericValues::new("value", [0., 1., 2., 4.]),
322    );
323    KDE_CALLS.with(|count| count.set(0));
324    let result = plot.stat_result().unwrap();
325    assert_eq!(KDE_CALLS.with(std::cell::Cell::get), 2);
326    let run = plot.render_with_results().unwrap();
327    assert_eq!(KDE_CALLS.with(std::cell::Cell::get), 4);
328    assert_eq!(result.density().len(), 128);
329    assert_eq!(run.results().len(), 1);
330}