Skip to main content

lichtung_plot/plots/histogram/
result.rs

1//! Scientific readback of the actual prepared bins and auxiliary domains.
2
3use std::sync::Arc;
4
5use super::HistogramSemantics;
6use crate::{
7    builder::PlotDescription,
8    data::{
9        DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload, DataRole, DataValue,
10        ExactInteger, IntegerValues, MemberAddress, SourceMembers,
11    },
12    elements::ElementRef,
13    plots::HistogramGeometry,
14    stats::{
15        results::{nullable_column, numeric_column as numeric, ResultDomains},
16        BinField, HistogramStat, StatResult,
17    },
18    Error, NumericValues, Result,
19};
20
21/// The scientific values of one histogram occurrence.
22///
23/// The geometry can be supplied directly to another histogram. A supplied
24/// geometry has no implicit sample count or inferred observation membership.
25#[derive(Debug, Clone)]
26pub struct HistogramResult(Arc<HistogramData>);
27
28#[derive(Debug)]
29struct HistogramData {
30    geometry: HistogramGeometry,
31    bins: StatResult,
32    denominator: Option<ExactInteger>,
33    kde_bandwidth: Option<f64>,
34    domains: ResultDomains,
35}
36
37impl HistogramResult {
38    /// Actual bin geometry and optional independent KDE and rug.
39    pub fn geometry(&self) -> &HistogramGeometry {
40        &self.0.geometry
41    }
42    /// Actual statistical fields of the bin domain.
43    pub fn bins(&self) -> &StatResult {
44        &self.0.bins
45    }
46    /// Meaning of the actual bin heights.
47    pub fn bin_stat(&self) -> HistogramStat {
48        self.0.geometry.get_bins().bin_stat()
49    }
50    /// Number of observations used by the generated histogram, if known.
51    pub fn denominator(&self) -> Option<&ExactInteger> {
52        self.0.denominator.as_ref()
53    }
54    /// Actual Scott bandwidth of the internally computed KDE, if any.
55    pub fn kde_bandwidth(&self) -> Option<f64> {
56        self.0.kde_bandwidth
57    }
58    /// Actual independent result domains.
59    pub fn domains(&self) -> &[DataDomainInfo] {
60        self.0.domains.infos()
61    }
62    /// Read the original contribution relation when the result has a unique domain.
63    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
64        self.0.domains.members(&address.into())
65    }
66
67    /// Read the original scientific contribution relation in the given domain.
68    pub fn members_in(
69        &self,
70        domain: &DataDomainRef,
71        address: impl Into<MemberAddress>,
72    ) -> Result<Option<SourceMembers>> {
73        self.0.domains.members_in(domain, &address.into())
74    }
75}
76
77fn finite(value: f64) -> Option<f64> {
78    value.is_finite().then_some(value)
79}
80
81fn supplied_members(domain: &DataDomainInfo) -> Result<Vec<Option<SourceMembers>>> {
82    crate::data::source::collect_source(
83        (0..domain.shape()[0])
84            .map(|slot| Ok(Some(SourceMembers::from_domains(&[domain], [slot])?))),
85    )
86}
87
88fn stat_field(stat: HistogramStat) -> BinField {
89    match stat {
90        HistogramStat::Count => BinField::Mass,
91        HistogramStat::Probability => BinField::Probability,
92        HistogramStat::Density => BinField::Density,
93    }
94}
95
96fn push_numeric_domain(
97    domains: &mut ResultDomains,
98    owner: &ElementRef,
99    columns: &[(&str, &NumericValues)],
100    members: Vec<Option<SourceMembers>>,
101) -> Result<()> {
102    let components = crate::data::source::collect_source(columns.iter().map(|(name, value)| {
103        DataComponentInfo::scientific_with_members(
104            name,
105            &DataPayload::Numeric((*value).clone()),
106            &members,
107        )
108    }))?;
109    domains.push(owner, None, components, members)?;
110    Ok(())
111}
112
113impl HistogramSemantics {
114    fn result_geometry(
115        &self,
116        source: &PlotDescription,
117        data: crate::data::PlotData<'_, '_>,
118    ) -> Result<HistogramGeometry> {
119        if let Some(supplied) = source.histogram_geometry_input() {
120            return Ok(supplied.clone());
121        }
122        let name = source
123            .x_col()
124            .ok_or_else(|| Error::Render("histogram has no sample field".into()))?;
125        let name = data.column(name)?.name();
126        let name = if name.trim().is_empty() {
127            "value"
128        } else {
129            name
130        };
131        let stat = source.histogram_stat_spec();
132        let mut geometry = HistogramGeometry::bins(
133            numeric("bin_lower", self.bins.iter().map(|bin| bin.lower))?,
134            numeric("bin_upper", self.bins.iter().map(|bin| bin.upper))?,
135            numeric(stat.name(), self.bins.iter().map(|bin| bin.height))?,
136            stat,
137        )
138        .value_dimension(name)
139        .height_dimension(stat.name());
140        if let Some(curve) = &self.curve {
141            if let crate::plots::HistogramComposite::KdeAndRug(kde) =
142                source.histogram_composite_spec()
143            {
144                let (x, y) = if let Some((x, y)) = kde.get_precomputed() {
145                    (x.clone(), y.clone())
146                } else {
147                    (
148                        numeric(name, curve.iter().map(|p| p.x))?,
149                        numeric("density", curve.iter().map(|p| p.y))?,
150                    )
151                };
152                geometry = geometry.kde(x, y);
153            }
154        }
155        if !self.rugs.is_empty() {
156            geometry = geometry.rug(
157                numeric(name, self.rugs.iter().map(|r| r.x))?,
158                numeric("baseline", self.rugs.iter().map(|r| r.baseline))?,
159                numeric("top", self.rugs.iter().map(|r| r.top))?,
160            );
161        }
162        Ok(geometry)
163    }
164
165    fn result_bins(
166        &self,
167        geometry: &HistogramGeometry,
168        originals: &[DataValue],
169        data: crate::data::PlotData<'_, '_>,
170        owner: &ElementRef,
171    ) -> Result<(StatResult, Option<ExactInteger>)> {
172        let bins = geometry.get_bins();
173        let stat = bins.bin_stat();
174        let mut columns = Vec::new();
175        crate::data::source::reserve_source(&mut columns, 10)?;
176        let mut push_numeric = |field: BinField, values: NumericValues| {
177            columns.push((field.into(), DataPayload::Numeric(values)));
178        };
179        push_numeric(BinField::Lower, bins.bin_lower().clone());
180        push_numeric(BinField::Upper, bins.bin_upper().clone());
181        push_numeric(
182            BinField::Center,
183            numeric(
184                "center",
185                self.bins.iter().map(|bin| bin.lower.midpoint(bin.upper)),
186            )?,
187        );
188        push_numeric(
189            BinField::Width,
190            nullable_column(
191                "width",
192                self.bins.iter().map(|bin| finite(bin.upper - bin.lower)),
193            )?,
194        );
195
196        let (members, denominator) = if let Some(contributions) = &self.contributions {
197            let samples = crate::data::select_value(originals, DataRole::Samples.into())?;
198            let members =
199                crate::data::source::collect_source(contributions.members.iter().map(|slots| {
200                    Ok(Some(SourceMembers::from_slots(
201                        &[&samples],
202                        slots.iter().map(|&row| data.row_index(row)),
203                    )?))
204                }))?;
205            let n = contributions.total;
206            let counts = IntegerValues::new(
207                "count",
208                contributions.counts.iter().copied().map(ExactInteger::from),
209            )?;
210            let fraction = |count: usize| count as f64 / n as f64;
211            push_numeric(
212                BinField::Probability,
213                if stat == HistogramStat::Probability {
214                    bins.bin_height().clone()
215                } else {
216                    numeric(
217                        "probability",
218                        contributions.counts.iter().map(|&count| fraction(count)),
219                    )?
220                },
221            );
222            push_numeric(
223                BinField::Percent,
224                numeric(
225                    "percent",
226                    contributions
227                        .counts
228                        .iter()
229                        .map(|&count| 100.0 * fraction(count)),
230                )?,
231            );
232            push_numeric(
233                BinField::Frequency,
234                nullable_column(
235                    "frequency",
236                    contributions
237                        .counts
238                        .iter()
239                        .zip(&self.bins)
240                        .map(|(&count, bin)| finite(count as f64 / (bin.upper - bin.lower))),
241                )?,
242            );
243            push_numeric(
244                BinField::Density,
245                if stat == HistogramStat::Density {
246                    bins.bin_height().clone()
247                } else {
248                    nullable_column(
249                        "density",
250                        contributions
251                            .counts
252                            .iter()
253                            .zip(&self.bins)
254                            .map(|(&count, bin)| finite(fraction(count) / (bin.upper - bin.lower))),
255                    )?
256                },
257            );
258            columns.push((BinField::Count.into(), DataPayload::Integer(counts.clone())));
259            columns.push((BinField::Mass.into(), DataPayload::Integer(counts)));
260            (members, Some(ExactInteger::from(n)))
261        } else {
262            let supplied = crate::data::select_value(originals, DataRole::Geometry.into())?;
263            let domain = &supplied.info().domains()[0];
264            let members = supplied_members(domain)?;
265            push_numeric(stat_field(stat), bins.bin_height().clone());
266            (members, None)
267        };
268        Ok((
269            StatResult::single_domain(owner, None, columns, members)?,
270            denominator,
271        ))
272    }
273
274    pub(crate) fn scientific_result(
275        &self,
276        source: &PlotDescription,
277        data: crate::data::PlotData<'_, '_>,
278        owner: &ElementRef,
279    ) -> Result<HistogramResult> {
280        let geometry = self.result_geometry(source, data)?;
281        let originals = source.primary_layer_data(&owner.declaration());
282        let (bins, denominator) = self.result_bins(&geometry, &originals, data, owner)?;
283        let mut domains = bins.result_domains().clone();
284        let supplied = originals
285            .iter()
286            .find(|value| value.info().role() == Some(DataRole::Geometry));
287        let samples = originals
288            .iter()
289            .find(|value| value.info().role() == Some(DataRole::Samples));
290
291        if let Some((x, y)) = geometry
292            .get_kde()
293            .and_then(crate::plots::HistogramKde::get_precomputed)
294        {
295            let members = if let Some(supplied) = supplied {
296                // Actual geometry declaration order: bins, optional KDE, optional rug.
297                supplied_members(&supplied.info().domains()[1])?
298            } else if self.kde_bandwidth.is_some() {
299                let whole = SourceMembers::from_slots(
300                    &[samples.expect("actual internal KDE sample role")],
301                    (0..data.height()).map(|row| data.row_index(row)),
302                )?;
303                crate::data::source::collect_source((0..x.len()).map(|_| Ok(Some(whole.clone()))))?
304            } else {
305                let kde = crate::data::select_value(&originals, DataRole::Kde.into())?;
306                supplied_members(&kde.info().domains()[0])?
307            };
308            push_numeric_domain(
309                &mut domains,
310                owner,
311                &[("kde_x", x), ("kde_density", y)],
312                members,
313            )?;
314        }
315        if let Some(rug) = geometry.get_rug() {
316            let members = if let Some(supplied) = supplied {
317                supplied_members(
318                    supplied
319                        .info()
320                        .domains()
321                        .last()
322                        .expect("actual supplied rug domain"),
323                )?
324            } else {
325                let samples = samples.expect("actual generated rug sample role");
326                crate::data::source::collect_source((0..rug.rug_x().len()).map(|row| {
327                    Ok(Some(SourceMembers::from_slots(
328                        &[samples],
329                        [data.row_index(row)],
330                    )?))
331                }))?
332            };
333            push_numeric_domain(
334                &mut domains,
335                owner,
336                &[
337                    ("rug_x", rug.rug_x()),
338                    ("rug_baseline", rug.rug_baseline()),
339                    ("rug_top", rug.rug_top()),
340                ],
341                members,
342            )?;
343        }
344        Ok(HistogramResult(crate::data::source::source_arc(
345            HistogramData {
346                geometry,
347                bins,
348                denominator,
349                kde_bandwidth: self.kde_bandwidth,
350                domains,
351            },
352        )?))
353    }
354}
355
356crate::orchestrator::science::stat_result_api!(
357    Histogram,
358    HistogramResult,
359    |source, data, layer| {
360        let theme = source.resolve_theme()?;
361        let (marks, _) = HistogramSemantics::new(source, data, &theme)?;
362        marks.scientific_result(source, data, layer)
363    }
364);