Skip to main content

lichtung_plot/plots/density/
result.rs

1//! Scientific values of an actual Gaussian density curve.
2
3use std::sync::Arc;
4
5use crate::{
6    data::{
7        DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload, DataRole, ExactInteger,
8        GroupKey, MemberAddress, SourceMembers,
9    },
10    elements::ElementRef,
11    errors::{Diagnostic, DiagnosticKind, DiagnosticReference, ErrorContext, OperationPhase},
12    stats::{results::numeric_column, DensityField, Kernel, StatResult},
13    Error, Result,
14};
15
16/// The actual evaluated density of one scientific group.
17#[derive(Debug, Clone)]
18pub struct DensityResult(Arc<DensityData>);
19
20#[derive(Debug)]
21struct DensityData {
22    fields: StatResult,
23    bandwidth: Option<f64>,
24    denominator: Option<ExactInteger>,
25    support: (f64, f64),
26    display: Option<DensityDisplayData>,
27}
28
29#[derive(Debug)]
30struct DensityDisplayData {
31    values: crate::NumericValues,
32    divisor: Option<f64>,
33    weight: Option<f64>,
34    common_count: Option<ExactInteger>,
35    domain: DataDomainInfo,
36}
37
38impl DensityResult {
39    /// The same actual evaluation fields consumed by scientific readback.
40    pub fn fields(&self) -> &StatResult {
41        &self.0.fields
42    }
43    /// Bandwidth used to evaluate the curve, absent for supplied values.
44    pub fn bandwidth(&self) -> Option<f64> {
45        self.0.bandwidth
46    }
47    /// Actual normalizing observation count, when known.
48    pub fn denominator(&self) -> Option<&ExactInteger> {
49        self.0.denominator.as_ref()
50    }
51    /// The actual Gaussian kernel.
52    pub const fn kernel(&self) -> Kernel {
53        Kernel::Gaussian
54    }
55    /// The first and last evaluated coordinates, independent of clipping.
56    pub fn support(&self) -> (f64, f64) {
57        self.0.support
58    }
59    /// Actual display density operands before projection or theme sizing.
60    /// Closure at zero and common-normalization weighting leave the raw density unchanged.
61    pub fn get_display_density(&self) -> Option<&crate::NumericValues> {
62        self.0.display.as_ref().map(|display| &display.values)
63    }
64    /// Actual shared maximum used as the marginal strip divisor, if applicable.
65    pub fn display_divisor(&self) -> Option<f64> {
66        self.0.display.as_ref().and_then(|display| display.divisor)
67    }
68    /// Actual group fraction used by Matrix common normalization, if applicable.
69    pub fn group_weight(&self) -> Option<f64> {
70        self.0.display.as_ref().and_then(|display| display.weight)
71    }
72    /// Exact total observation count used by common normalization, if applicable.
73    pub fn common_norm_count(&self) -> Option<&ExactInteger> {
74        self.0
75            .display
76            .as_ref()
77            .and_then(|display| display.common_count.as_ref())
78    }
79    /// Actual independent scientific result domains.
80    pub fn domains(&self) -> &[DataDomainInfo] {
81        self.0.display.as_ref().map_or_else(
82            || self.0.fields.domains(),
83            |display| std::slice::from_ref(&display.domain),
84        )
85    }
86    /// Original members of an evaluation node.
87    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
88        self.0.fields.result_domains().members(&address.into())
89    }
90    /// Original members in the actual result domain.
91    pub fn members_in(
92        &self,
93        domain: &DataDomainRef,
94        address: impl Into<MemberAddress>,
95    ) -> Result<Option<SourceMembers>> {
96        self.0.fields.members_in(domain, address)
97    }
98
99    pub(crate) fn from_curve(
100        values: DensityValues<'_>,
101        chart: &crate::builder::PlotDescription,
102        owner: &ElementRef,
103        identity: &crate::data::CollectivePair,
104        members: &SourceMembers,
105    ) -> Result<Self> {
106        let keys = crate::data::group_key::CollectiveKeys::new(chart, identity)?;
107        let group = keys.key();
108        let x = numeric_column(values.name, values.grid.iter().copied())?;
109        let density = numeric_column("density", values.densities.iter().copied())?;
110        let mut columns = vec![
111            (DensityField::X.into(), DataPayload::Numeric(x)),
112            (DensityField::Density.into(), DataPayload::Numeric(density)),
113        ];
114        for (field, key) in [
115            (DensityField::Group, keys.group.as_ref()),
116            (DensityField::Hue, keys.hue.as_ref()),
117        ] {
118            if let Some((name, key)) = key {
119                crate::data::source::reserve_source(&mut columns, 1)?;
120                columns.push((
121                    field.into(),
122                    crate::data::group_key::key_column(
123                        name,
124                        std::iter::repeat_n(key.clone(), values.grid.len()),
125                    )?,
126                ));
127            }
128        }
129        let relations = crate::data::source::collect_source(
130            (0..values.grid.len()).map(|_| Ok(Some(members.clone()))),
131        )?;
132        let fields = StatResult::single_domain(owner, group.as_ref(), columns, relations)?;
133        let display = values
134            .display
135            .map(|display| {
136                let values = numeric_column("display_density", display.values.iter().copied())?;
137                let domain =
138                    fields.domains()[0]
139                        .clone()
140                        .with_component(DataComponentInfo::scientific(
141                            "get_display_density",
142                            &DataPayload::Numeric(values.clone()),
143                        )?)?;
144                Ok::<_, Error>(DensityDisplayData {
145                    values,
146                    divisor: display.divisor,
147                    weight: display.weight,
148                    common_count: display.common_count.map(ExactInteger::from),
149                    domain,
150                })
151            })
152            .transpose()?;
153        Ok(Self(crate::data::source::source_arc(DensityData {
154            fields,
155            display,
156            bandwidth: Some(values.bandwidth),
157            denominator: Some(values.denominator.into()),
158            support: (
159                *values.grid.first().expect("actual evaluated nodes"),
160                *values.grid.last().expect("actual evaluated nodes"),
161            ),
162        })?))
163    }
164
165    pub(crate) fn select(results: Vec<Self>, group: Option<&GroupKey>) -> Result<Self> {
166        let matches = crate::data::source::collect_source(
167            results
168                .into_iter()
169                .filter(|result| {
170                    group.is_none() || result.domains()[0].reference().group_key() == group
171                })
172                .map(Ok),
173        )?;
174        match matches.as_slice() {
175            [result] => Ok(result.clone()),
176            [] => Err(Error::Data(
177                Diagnostic::new(
178                    DiagnosticKind::UnknownKey {
179                        key: group.map(|group| crate::data::RawKey::Tuple(group.keys().to_vec())),
180                    },
181                    "density has no result for the selected group",
182                )
183                .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare)),
184            )),
185            _ => Err(Error::Data(
186                Diagnostic::new(
187                    DiagnosticKind::Ambiguous {
188                        candidates: matches
189                            .iter()
190                            .map(|result| {
191                                DiagnosticReference::Domain(result.domains()[0].reference().clone())
192                            })
193                            .collect(),
194                    },
195                    "density has several scientific groups; select an actual group",
196                )
197                .with_context(ErrorContext::new().with_operation(OperationPhase::Prepare)),
198            )),
199        }
200    }
201}
202
203#[derive(Clone, Copy)]
204pub(crate) struct DensityValues<'a> {
205    pub(crate) name: &'a str,
206    pub(crate) grid: &'a [f64],
207    pub(crate) densities: &'a [f64],
208    pub(crate) bandwidth: f64,
209    pub(crate) denominator: usize,
210    pub(crate) display: Option<DensityDisplay<'a>>,
211}
212
213#[derive(Clone, Copy)]
214pub(crate) struct DensityDisplay<'a> {
215    pub(crate) values: &'a [f64],
216    pub(crate) divisor: Option<f64>,
217    pub(crate) weight: Option<f64>,
218    pub(crate) common_count: Option<usize>,
219}
220
221impl super::PreparedDensity {
222    pub(crate) fn scientific_results(
223        &self,
224        chart: &crate::builder::PlotDescription,
225        owner: &ElementRef,
226    ) -> Result<Vec<DensityResult>> {
227        let originals = chart.primary_layer_data(&owner.declaration());
228        let samples = crate::data::select_value(&originals, DataRole::Value.into())?;
229        let name = samples.info().name().unwrap_or("value");
230        crate::data::source::collect_source(self.curves.iter().map(|curve| {
231            let capture = curve.capture.as_ref().expect("actual result capture");
232            let members = SourceMembers::from_slots(&[&samples], capture.slots.iter().copied())?;
233            DensityResult::from_curve(
234                DensityValues {
235                    name,
236                    grid: &curve.grid,
237                    densities: &curve.densities,
238                    bandwidth: capture.bandwidth,
239                    denominator: capture.slots.len(),
240                    display: None,
241                },
242                chart,
243                owner,
244                &curve.identity,
245                &members,
246            )
247        }))
248    }
249}
250
251impl crate::Plot<crate::kind::Density> {
252    /// Prepare the unique density group without fonts or layout.
253    pub fn stat_result(&self) -> Result<DensityResult> {
254        self.stat_result_with_operation(&crate::operation::OperationOptions::default())
255    }
256    /// Prepare with explicit per-call resource options.
257    pub fn stat_result_with_operation(
258        &self,
259        options: &crate::operation::OperationOptions,
260    ) -> Result<DensityResult> {
261        self.stat_result_in_with_operation(&crate::layout::PanelPath::root(), options)
262    }
263    /// Prepare the unique group of an actual selected panel.
264    pub fn stat_result_in(&self, panel: &crate::layout::PanelPath) -> Result<DensityResult> {
265        self.stat_result_in_with_operation(panel, &crate::operation::OperationOptions::default())
266    }
267    /// Prepare the selected panel with operation options.
268    pub fn stat_result_in_with_operation(
269        &self,
270        panel: &crate::layout::PanelPath,
271        options: &crate::operation::OperationOptions,
272    ) -> Result<DensityResult> {
273        self.stat_result_selected(panel, None, options)
274    }
275    /// Prepare an explicit original group of the selected panel.
276    pub fn stat_result_group(
277        &self,
278        panel: &crate::layout::PanelPath,
279        group: &GroupKey,
280    ) -> Result<DensityResult> {
281        self.stat_result_group_with_operation(
282            panel,
283            group,
284            &crate::operation::OperationOptions::default(),
285        )
286    }
287    /// Prepare an explicit original group with per-call options.
288    pub fn stat_result_group_with_operation(
289        &self,
290        panel: &crate::layout::PanelPath,
291        group: &GroupKey,
292        options: &crate::operation::OperationOptions,
293    ) -> Result<DensityResult> {
294        self.stat_result_selected(panel, Some(group), options)
295    }
296
297    fn stat_result_selected(
298        &self,
299        panel: &crate::layout::PanelPath,
300        group: Option<&GroupKey>,
301        options: &crate::operation::OperationOptions,
302    ) -> Result<DensityResult> {
303        let chart = self.description();
304        crate::orchestrator::science::with_scope(chart, panel, options, |data, layer| {
305            let parent = (!data.is_full_plot())
306                .then(|| crate::data::observed_source_collectives(chart, "density facet channels"))
307                .transpose()?;
308            let prepared = super::PreparedDensity::new_selected(
309                chart,
310                data,
311                parent.as_ref().map(|parent| parent.identities.as_slice()),
312                group,
313            )?;
314            DensityResult::select(prepared.scientific_results(chart, layer)?, group)
315        })
316    }
317}