lichtung_plot/plots/matrix/
result.rs1use crate::{
4 builder::PlotDescription,
5 data::{ComponentPathPart, DataRole, GroupKey, PlotData, SourceMembers},
6 elements::ElementRef,
7 layout::{PanelPath, PanelStep},
8 operation::OperationOptions,
9 plots::{
10 density::result::{DensityDisplay, DensityValues},
11 DensityResult,
12 },
13 Result,
14};
15
16impl super::PreparedMatrixAxes {
17 pub(crate) fn scientific_results(
18 &self,
19 chart: &PlotDescription,
20 owner: &ElementRef,
21 column: usize,
22 ) -> Result<Vec<DensityResult>> {
23 diagonal_results(
24 chart,
25 owner,
26 &self.groups,
27 column,
28 column,
29 &self.diagonals[column],
30 )
31 }
32}
33
34fn diagonal_results(
35 chart: &PlotDescription,
36 owner: &ElementRef,
37 groups: &[super::HueGroup],
38 column: usize,
39 sample_column: usize,
40 density: &super::MatrixDensity,
41) -> Result<Vec<DensityResult>> {
42 let variables = chart.matrix_variables().expect("actual matrix variables");
43 let variable = variables.get_at(column).expect("actual diagonal variable");
44 let originals = chart.primary_layer_data(&owner.declaration());
45 let inputs = crate::data::select_value(&originals, DataRole::Variables.into())?;
46 let [domain] = inputs.info().domains() else {
47 return Err(crate::Error::Render(
48 "matrix variables have no observation domain".into(),
49 ));
50 };
51 let path = [
52 ComponentPathPart::Field("variables".into()),
53 ComponentPathPart::Key(variable.key.clone()),
54 ComponentPathPart::Field("values".into()),
55 ];
56 let component = domain
57 .components()
58 .iter()
59 .find(|component| component.path() == path)
60 .expect("actual variable source");
61 crate::data::source::collect_source(groups.iter().zip(&density.curves).map(|(group, curve)| {
62 let members = SourceMembers::from_component_slots(
63 domain,
64 component,
65 group.alphas.iter().map(|alpha| alpha.slot),
66 )?;
67 let display = crate::data::source::collect_source(curve.weighted_values().map(Ok))?;
68 DensityResult::from_curve(
69 DensityValues {
70 name: variable.values.name(),
71 grid: &density.positions,
72 densities: &curve.values,
73 bandwidth: group.bandwidths[sample_column],
74 denominator: group.alphas.len(),
75 display: Some(DensityDisplay {
76 values: &display,
77 divisor: None,
78 weight: Some(curve.weight),
79 common_count: Some(density.count),
80 }),
81 },
82 chart,
83 owner,
84 &group.identity,
85 &members,
86 )
87 }))
88}
89
90fn column_index(chart: &PlotDescription, panel: &PanelPath) -> Result<usize> {
91 let [PanelStep::Matrix(x, y)] = panel.steps() else {
92 return Err(crate::Error::Data(
93 "select an actual Matrix diagonal variable".into(),
94 ));
95 };
96 if x != y {
97 return Err(crate::Error::Data(
98 "an off-diagonal Matrix scatter region has no density result".into(),
99 ));
100 }
101 let variables = chart.matrix_variables().expect("actual matrix variables");
102 variables.get(x)?;
103 Ok(variables
104 .variables()
105 .iter()
106 .position(|variable| &variable.key == x)
107 .expect("validated variable"))
108}
109
110fn prepare_result(
111 chart: &PlotDescription,
112 data: PlotData<'_, '_>,
113 owner: &ElementRef,
114 column: usize,
115 selected: Option<&GroupKey>,
116) -> Result<Vec<DensityResult>> {
117 let variables = chart.matrix_variables().expect("actual matrix variables");
118 let name = variables
119 .get_at(column)
120 .expect("actual diagonal variable")
121 .values
122 .raw_name();
123 let (groups, _) = super::build_groups(chart, &[name], data, None)?;
124 let range =
125 super::matrix_support_range(&groups, 0, name, chart.group_name(), chart.hue_name())?;
126 let count = groups.iter().map(|group| group.alphas.len()).sum();
127 let groups = if let Some(selected) = selected {
128 let mut retained = Vec::new();
129 for group in groups {
130 if crate::data::group_key::CollectiveKeys::new(chart, &group.identity)?
131 .key()
132 .as_ref()
133 == Some(selected)
134 {
135 crate::data::source::reserve_source(&mut retained, 1)?;
136 retained.push(group);
137 }
138 }
139 retained
140 } else {
141 groups
142 };
143 if groups.is_empty() {
144 return Ok(Vec::new());
145 }
146 let (density, _) = super::prepare_density(chart, &groups, 0, name, range, count)?;
147 diagonal_results(chart, owner, &groups, column, 0, &density)
148}
149
150impl crate::Plot<crate::kind::Matrix> {
151 pub fn stat_result_in(&self, panel: &PanelPath) -> Result<DensityResult> {
153 self.stat_result_in_with_operation(panel, &OperationOptions::default())
154 }
155
156 pub fn stat_result_in_with_operation(
158 &self,
159 panel: &PanelPath,
160 options: &OperationOptions,
161 ) -> Result<DensityResult> {
162 self.stat_result_selected(panel, None, options)
163 }
164
165 pub fn stat_result_group(&self, panel: &PanelPath, group: &GroupKey) -> Result<DensityResult> {
167 self.stat_result_group_with_operation(panel, group, &OperationOptions::default())
168 }
169
170 pub fn stat_result_group_with_operation(
172 &self,
173 panel: &PanelPath,
174 group: &GroupKey,
175 options: &OperationOptions,
176 ) -> Result<DensityResult> {
177 self.stat_result_selected(panel, Some(group), options)
178 }
179
180 fn stat_result_selected(
181 &self,
182 panel: &PanelPath,
183 group: Option<&GroupKey>,
184 options: &OperationOptions,
185 ) -> Result<DensityResult> {
186 let chart = self.description();
187 let column = column_index(chart, panel)?;
188 crate::orchestrator::science::with_scope(chart, panel, options, |data, owner| {
189 DensityResult::select(prepare_result(chart, data, owner, column, group)?, group)
190 })
191 }
192}
193
194#[cfg(test)]
195#[test]
196fn independent_diagonal_estimates_only_the_requested_group_with_common_normalization() {
197 use crate::stats::distribution::KDE_CALLS;
198 use crate::stats::DensityField;
199 use crate::{CategoryValues, NumericValues, Plot};
200
201 let plot = Plot::matrix(vec![
202 NumericValues::new("x", [0., 1., 2., 10., 12.]),
203 NumericValues::new("y", [1., 3., 4., 5., 6.]),
204 ])
205 .group(CategoryValues::new("group", ["A", "A", "A", "B", "B"]).unwrap());
206 let panel = PanelPath::root().matrix("x", "x");
207 let group = GroupKey::single("B");
208 KDE_CALLS.with(|count| count.set(0));
209 let selected = plot.stat_result_group(&panel, &group).unwrap();
210 assert_eq!(KDE_CALLS.with(std::cell::Cell::get), 1);
211 let run = plot.render_with_results().unwrap();
212 assert_eq!(KDE_CALLS.with(std::cell::Cell::get), 5);
213 let result = run
214 .results()
215 .iter()
216 .find(|entry| entry.panel() == &panel && entry.group() == Some(&group))
217 .unwrap();
218 let crate::stats::ScientificResult::Density(result) = result.value() else {
219 panic!("actual diagonal")
220 };
221 let crate::data::DataPayload::Numeric(selected_values) =
222 selected.fields().values(DensityField::Density).unwrap()
223 else {
224 panic!("numeric density")
225 };
226 let crate::data::DataPayload::Numeric(actual_values) =
227 result.fields().values(DensityField::Density).unwrap()
228 else {
229 panic!("numeric density")
230 };
231 assert_eq!(selected_values, actual_values);
232 assert_eq!(selected.common_norm_count(), result.common_norm_count());
233}