Skip to main content

lichtung_plot/plots/regression/
result.rs

1//! The owning values of a simple OLS scientific preparation.
2
3use std::sync::Arc;
4
5use crate::{
6    data::{
7        AxisValues, Bounds, DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload,
8        DataRole, ExactInteger, MemberAddress, RawKey, SourceMembers, SourceRows,
9    },
10    elements::{ElementRef, LayerSlot},
11    layout::PanelPath,
12    stats::{
13        results::{nullable_column, numeric_column, ResultDomains},
14        FitField, StatResult,
15    },
16    BooleanValues, NumericValues, Result,
17};
18
19/// Actual scientific model declaration.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum Fit {
23    /// Simple ordinary least squares with an intercept.
24    Ols,
25}
26
27impl Fit {
28    /// The native simple least-squares model.
29    pub const fn ols() -> Self {
30        Self::Ols
31    }
32}
33
34/// Original response representation of a fitted model.
35#[derive(Debug, Clone)]
36#[non_exhaustive]
37pub enum FitResponse {
38    /// Original numeric response.
39    Numeric(NumericValues),
40}
41
42/// Coefficients in the original predictor/response space.
43#[derive(Debug, Clone)]
44pub struct FitCoefficients {
45    keys: Arc<[RawKey]>,
46    values: NumericValues,
47}
48
49impl FitCoefficients {
50    /// Ordered intercept and predictor term identities.
51    pub fn keys(&self) -> &[RawKey] {
52        &self.keys
53    }
54    /// Actual fitted coefficients in the same order.
55    pub fn values(&self) -> &NumericValues {
56        &self.values
57    }
58}
59
60/// Model parameters derived by the actual fit.
61#[derive(Debug, Clone)]
62pub struct FitParameters {
63    coefficients: FitCoefficients,
64}
65
66impl FitParameters {
67    /// Coefficients when the selected model has them.
68    pub fn get_coefficients(&self) -> Option<&FitCoefficients> {
69        Some(&self.coefficients)
70    }
71}
72
73/// Owning original observation domain, including non-participating records.
74#[derive(Debug, Clone)]
75pub struct FitObservationRows {
76    original_x: AxisValues,
77    original_y: FitResponse,
78    used: BooleanValues,
79    fitted: NumericValues,
80    residual: NumericValues,
81    original_slots: Arc<[usize]>,
82    source_rows: Option<SourceRows>,
83    domains: ResultDomains,
84}
85
86impl FitObservationRows {
87    /// Original predictor values in logical source order.
88    pub fn original_x(&self) -> &AxisValues {
89        &self.original_x
90    }
91    /// Original response, retaining its actual validity.
92    pub fn original_y(&self) -> &FitResponse {
93        &self.original_y
94    }
95    /// Whether each original record participated in training.
96    pub fn used(&self) -> &BooleanValues {
97        &self.used
98    }
99    /// Actual fitted values on participating observations.
100    pub fn fitted(&self) -> &NumericValues {
101        &self.fitted
102    }
103    /// Actual response residuals on participating observations.
104    pub fn residual(&self) -> &NumericValues {
105        &self.residual
106    }
107    /// Original bound logical slots, before filtering or faceting.
108    pub fn original_slots(&self) -> &[usize] {
109        &self.original_slots
110    }
111    /// Original supplied IDs when explicitly present.
112    pub fn source_rows(&self) -> Option<&SourceRows> {
113        self.source_rows.as_ref()
114    }
115    /// Original paired-variable relations in this observation domain.
116    pub fn members(&self) -> &[Option<SourceMembers>] {
117        self.domains
118            .relation(self.domains.infos()[0].reference())
119            .expect("actual observation domain")
120    }
121}
122
123/// Actual prediction grid and its optional mean-response bounds.
124#[derive(Debug, Clone)]
125pub struct FitPredictionRows {
126    x: AxisValues,
127    fitted: NumericValues,
128    bounds: Option<Bounds>,
129    fields: StatResult,
130}
131
132impl FitPredictionRows {
133    /// Actual original-space prediction coordinates.
134    pub fn x(&self) -> &AxisValues {
135        &self.x
136    }
137    /// Actual responses on the prediction grid.
138    pub fn fitted(&self) -> &NumericValues {
139        &self.fitted
140    }
141    /// Actual optional interval endpoints, without generating new predictions.
142    pub fn bounds(&self) -> Option<&Bounds> {
143        self.bounds.as_ref()
144    }
145    /// Original training members of the actual prediction domain.
146    pub fn members(&self) -> &[Option<SourceMembers>] {
147        self.fields
148            .get_members(FitField::X)
149            .expect("actual prediction domain")
150    }
151}
152
153/// Diagnostics available from the fitted simple OLS model.
154#[derive(Debug, Clone)]
155pub struct FitDiagnostics {
156    rank: usize,
157    df: ExactInteger,
158    r_squared: f64,
159    rss: Option<f64>,
160    leverage: NumericValues,
161}
162
163impl FitDiagnostics {
164    /// Actual design rank.
165    pub fn rank(&self) -> Option<usize> {
166        Some(self.rank)
167    }
168    /// Exact residual degrees of freedom.
169    pub fn df(&self) -> Option<&ExactInteger> {
170        Some(&self.df)
171    }
172    /// Actual coefficient of determination.
173    pub fn r_squared(&self) -> f64 {
174        self.r_squared
175    }
176    /// Residual sum of squares, when representable in the original response space.
177    pub fn residual_sum_squares(&self) -> Option<f64> {
178        self.rss
179    }
180    /// Actual leverage values on participating training observations.
181    pub fn get_leverage(&self) -> Option<&NumericValues> {
182        Some(&self.leverage)
183    }
184}
185
186/// The actual model values for one panel and training group.
187#[derive(Debug, Clone)]
188pub struct FitGroupResult {
189    owner: ElementRef,
190    observations: FitObservationRows,
191    predictions: FitPredictionRows,
192    parameters: FitParameters,
193    diagnostics: FitDiagnostics,
194}
195
196impl FitGroupResult {
197    /// Actual scientific panel.
198    pub fn panel(&self) -> &PanelPath {
199        self.owner.panel()
200    }
201    /// Actual declaring layer.
202    pub fn layer_slot(&self) -> LayerSlot {
203        self.owner.layer_slot()
204    }
205    /// Actual group key, absent for the current ungrouped OLS model.
206    pub const fn group_key(&self) -> Option<&crate::data::GroupKey> {
207        None
208    }
209    /// Original observation domain.
210    pub fn observations(&self) -> &FitObservationRows {
211        &self.observations
212    }
213    /// Actual independent prediction domain.
214    pub fn predictions(&self) -> &FitPredictionRows {
215        &self.predictions
216    }
217    /// Actual fitted parameters.
218    pub fn parameters(&self) -> &FitParameters {
219        &self.parameters
220    }
221    /// Actual available diagnostics.
222    pub fn diagnostics(&self) -> &FitDiagnostics {
223        &self.diagnostics
224    }
225}
226
227/// A complete owning native fit from one scientific preparation.
228#[derive(Debug, Clone)]
229pub struct FitResult {
230    groups: Arc<[FitGroupResult]>,
231    domains: ResultDomains,
232}
233
234impl FitResult {
235    /// Model used in this preparation.
236    pub const fn get_model(&self) -> Fit {
237        Fit::Ols
238    }
239    /// Actual training groups.
240    pub fn groups(&self) -> &[FitGroupResult] {
241        &self.groups
242    }
243    /// Shared actual prediction fields, not a second fit.
244    pub fn stat_fields(&self) -> &StatResult {
245        &self.groups[0].predictions.fields
246    }
247    /// Actual observation and prediction domains.
248    pub fn domains(&self) -> &[DataDomainInfo] {
249        self.domains.infos()
250    }
251    /// Read a member of an actual result domain.
252    pub fn members_in(
253        &self,
254        domain: &DataDomainRef,
255        address: impl Into<MemberAddress>,
256    ) -> Result<Option<SourceMembers>> {
257        self.domains.members_in(domain, &address.into())
258    }
259    /// Read a member when the result has a single actual domain.
260    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
261        self.domains.members(&address.into())
262    }
263}
264
265fn finite(value: f64) -> Option<f64> {
266    value.is_finite().then_some(value)
267}
268
269impl super::PreparedRegression {
270    fn result_observations(
271        &self,
272        source: &crate::builder::PlotDescription,
273        data: crate::data::PlotData<'_, '_>,
274        owner: &ElementRef,
275        x: &crate::data::DataValue,
276        y: &crate::data::DataValue,
277    ) -> Result<(FitObservationRows, NumericValues)> {
278        let capture = self.capture.as_ref().expect("actual captured fit");
279        let raw_x = x.numeric()?;
280        let raw_y = y.numeric()?;
281        let original_slots = crate::data::source::collect_source(
282            (0..data.height()).map(|row| Ok(data.row_index(row))),
283        )?;
284        let training = [x, y];
285        let observations_members = crate::data::source::collect_source(
286            original_slots
287                .iter()
288                .map(|&slot| Ok(Some(SourceMembers::from_slots(&training, [slot])?))),
289        )?;
290        let source_rows = source
291            .source_row_map()
292            .map(|rows| {
293                SourceRows::new(
294                    original_slots
295                        .iter()
296                        .map(|&slot| rows.get(slot).expect("actual original ID")),
297                )
298            })
299            .transpose()?;
300
301        // The admitted OLS rows are retained in source order. The native fit's
302        // observation values come from its original residual pass.
303        let mut used_values = Vec::new();
304        let mut fitted_values = Vec::new();
305        let mut residual_values = Vec::new();
306        let mut leverage_values = Vec::new();
307        for values in [
308            &mut fitted_values,
309            &mut residual_values,
310            &mut leverage_values,
311        ] {
312            crate::data::source::reserve_source(values, original_slots.len())?;
313        }
314        crate::data::source::reserve_source(&mut used_values, original_slots.len())?;
315        for &slot in &original_slots {
316            crate::operation::work(1)?;
317            let index = self
318                .alphas
319                .binary_search_by_key(&slot, |alpha| alpha.slot)
320                .ok();
321            let observation =
322                index.map(|at| &capture.fit.observations().expect("actual diagnostics")[at]);
323            used_values.push(index.is_some());
324            fitted_values.push(observation.and_then(|value| finite(value.fitted)));
325            residual_values.push(observation.and_then(|value| finite(value.residual)));
326            leverage_values.push(observation.and_then(|value| finite(value.leverage)));
327        }
328        crate::operation::memory(used_values.len() as u128 * std::mem::size_of::<bool>() as u128)?;
329        let used = BooleanValues::new("used", used_values);
330        let fitted = nullable_column("fitted", fitted_values.into_iter())?;
331        let residual = nullable_column("residual", residual_values.into_iter())?;
332        let leverage = nullable_column("leverage", leverage_values.into_iter())?;
333        // Own the same original values, including present NaN and null.
334        crate::operation::memory(
335            original_slots.len() as u128
336                * 2
337                * (std::mem::size_of::<f64>() + std::mem::size_of::<Option<f64>>()) as u128,
338        )?;
339        let original_x = raw_x.select(&original_slots)?;
340        let original_y = raw_y.select(&original_slots)?;
341        let mut domains = ResultDomains::default();
342        let components = crate::data::source::collect_source(
343            [
344                ("original_x", DataPayload::Numeric(original_x.clone())),
345                ("original_y", DataPayload::Numeric(original_y.clone())),
346                ("used", DataPayload::Boolean(used.clone())),
347                ("fitted", DataPayload::Numeric(fitted.clone())),
348                ("residual", DataPayload::Numeric(residual.clone())),
349                ("leverage", DataPayload::Numeric(leverage.clone())),
350            ]
351            .into_iter()
352            .map(|(name, values)| {
353                DataComponentInfo::scientific_with_members(name, &values, &observations_members)
354            }),
355        )?;
356        domains.push_info(
357            DataDomainInfo::bound(
358                DataDomainRef::scientific(owner, None),
359                original_slots.len(),
360                source_rows.as_ref(),
361                components,
362            ),
363            observations_members,
364        )?;
365        Ok((
366            FitObservationRows {
367                original_x: AxisValues::Numeric(original_x),
368                original_y: FitResponse::Numeric(original_y),
369                used,
370                fitted,
371                residual,
372                original_slots: original_slots.into(),
373                source_rows,
374                domains,
375            },
376            leverage,
377        ))
378    }
379
380    fn result_predictions(
381        &self,
382        owner: &ElementRef,
383        predictor_name: &str,
384        all_members: &SourceMembers,
385    ) -> Result<FitPredictionRows> {
386        let capture = self.capture.as_ref().expect("actual captured fit");
387        let (predict_x, predicted, bounds) = if let Some(values) = &self.band_values {
388            (
389                numeric_column(predictor_name, values.iter().map(|v| v.0))?,
390                numeric_column("fitted", capture.predicted.iter().copied())?,
391                Some(Bounds::new(
392                    numeric_column("lower", values.iter().map(|v| v.1))?,
393                    numeric_column("upper", values.iter().map(|v| v.2))?,
394                )),
395            )
396        } else {
397            (
398                numeric_column(predictor_name, self.fit_line.iter().map(|v| v.0))?,
399                numeric_column("fitted", self.fit_line.iter().map(|v| v.1))?,
400                None,
401            )
402        };
403        let mut columns = vec![
404            (FitField::X.into(), DataPayload::Numeric(predict_x.clone())),
405            (
406                FitField::Fitted.into(),
407                DataPayload::Numeric(predicted.clone()),
408            ),
409        ];
410        if let Some(bounds) = &bounds {
411            crate::data::source::reserve_source(&mut columns, 2)?;
412            columns.push((
413                FitField::Lower.into(),
414                DataPayload::Numeric(bounds.lower().clone()),
415            ));
416            columns.push((
417                FitField::Upper.into(),
418                DataPayload::Numeric(bounds.upper().clone()),
419            ));
420        }
421        let relations = crate::data::source::collect_source(
422            (0..predict_x.len()).map(|_| Ok(Some(all_members.clone()))),
423        )?;
424        let fields = StatResult::single_domain(owner, None, columns, relations)?;
425        Ok(FitPredictionRows {
426            x: AxisValues::Numeric(predict_x),
427            fitted: predicted,
428            bounds,
429            fields,
430        })
431    }
432
433    pub(crate) fn scientific_result(
434        &self,
435        source: &crate::builder::PlotDescription,
436        data: crate::data::PlotData<'_, '_>,
437        owner: &ElementRef,
438    ) -> Result<FitResult> {
439        let capture = self.capture.as_ref().expect("actual fitted result capture");
440        let originals = source.primary_layer_data(&owner.declaration());
441        let x = crate::data::select_value(&originals, DataRole::X.into())?;
442        let y = crate::data::select_value(&originals, DataRole::Y.into())?;
443        let raw_x = x.numeric()?;
444        let (observations, leverage) = self.result_observations(source, data, owner, &x, &y)?;
445        let all_members =
446            SourceMembers::from_slots(&[&x, &y], self.alphas.iter().map(|alpha| alpha.slot))?;
447        let predictions = self.result_predictions(owner, raw_x.name(), &all_members)?;
448        let mut domains = observations.domains.clone();
449        domains.extend(predictions.fields.result_domains())?;
450        let (intercept, slope, r_squared) = capture.fit.coefficients();
451        let coefficients = FitCoefficients {
452            keys: Arc::from([RawKey::from("intercept"), RawKey::from("slope")]),
453            values: numeric_column("coefficient", [intercept, slope].into_iter())?,
454        };
455        let terms = crate::data::RawKeyValues::new("term", coefficients.keys.iter().cloned())?;
456        let coefficient_components = vec![
457            DataComponentInfo::scientific("keys", &DataPayload::RawKeys(terms.clone()))?,
458            DataComponentInfo::scientific(
459                "values",
460                &DataPayload::Numeric(coefficients.values.clone()),
461            )?,
462        ];
463        let info = DataDomainInfo::bound(
464            DataDomainRef::scientific(owner, None),
465            terms.len(),
466            None,
467            coefficient_components,
468        )
469        .with_keys(&terms);
470        domains.push_info(
471            info,
472            crate::data::source::collect_source(
473                (0..terms.len()).map(|_| Ok(Some(all_members.clone()))),
474            )?,
475        )?;
476        let diagnostics = FitDiagnostics {
477            rank: 2,
478            df: ExactInteger::from(self.alphas.len() - 2),
479            r_squared,
480            rss: capture.fit.residual_sum_squares(),
481            leverage,
482        };
483        let group = FitGroupResult {
484            owner: owner.clone(),
485            observations,
486            predictions,
487            parameters: FitParameters { coefficients },
488            diagnostics,
489        };
490        Ok(FitResult {
491            groups: Arc::from([group]),
492            domains,
493        })
494    }
495}
496
497crate::orchestrator::science::stat_result_api!(Regression, FitResult, |source, data, layer| {
498    super::PreparedRegression::new(source, data)?
499        .0
500        .scientific_result(source, data, layer)
501});