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::check()?;
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::check()?;
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        let original_x = raw_x.select(&original_slots)?;
335        let original_y = raw_y.select(&original_slots)?;
336        let mut domains = ResultDomains::default();
337        let components = crate::data::source::collect_source(
338            [
339                ("original_x", DataPayload::Numeric(original_x.clone())),
340                ("original_y", DataPayload::Numeric(original_y.clone())),
341                ("used", DataPayload::Boolean(used.clone())),
342                ("fitted", DataPayload::Numeric(fitted.clone())),
343                ("residual", DataPayload::Numeric(residual.clone())),
344                ("leverage", DataPayload::Numeric(leverage.clone())),
345            ]
346            .into_iter()
347            .map(|(name, values)| {
348                DataComponentInfo::scientific_with_members(name, &values, &observations_members)
349            }),
350        )?;
351        domains.push_info(
352            DataDomainInfo::bound(
353                DataDomainRef::scientific(owner, None),
354                original_slots.len(),
355                source_rows.as_ref(),
356                components,
357            ),
358            observations_members,
359        )?;
360        Ok((
361            FitObservationRows {
362                original_x: AxisValues::Numeric(original_x),
363                original_y: FitResponse::Numeric(original_y),
364                used,
365                fitted,
366                residual,
367                original_slots: original_slots.into(),
368                source_rows,
369                domains,
370            },
371            leverage,
372        ))
373    }
374
375    fn result_predictions(
376        &self,
377        owner: &ElementRef,
378        predictor_name: &str,
379        all_members: &SourceMembers,
380    ) -> Result<FitPredictionRows> {
381        let capture = self.capture.as_ref().expect("actual captured fit");
382        let (predict_x, predicted, bounds) = if let Some(values) = &self.band_values {
383            (
384                numeric_column(predictor_name, values.iter().map(|v| v.0))?,
385                numeric_column("fitted", capture.predicted.iter().copied())?,
386                Some(Bounds::new(
387                    numeric_column("lower", values.iter().map(|v| v.1))?,
388                    numeric_column("upper", values.iter().map(|v| v.2))?,
389                )),
390            )
391        } else {
392            (
393                numeric_column(predictor_name, self.fit_line.iter().map(|v| v.0))?,
394                numeric_column("fitted", self.fit_line.iter().map(|v| v.1))?,
395                None,
396            )
397        };
398        let mut columns = vec![
399            (FitField::X.into(), DataPayload::Numeric(predict_x.clone())),
400            (
401                FitField::Fitted.into(),
402                DataPayload::Numeric(predicted.clone()),
403            ),
404        ];
405        if let Some(bounds) = &bounds {
406            crate::data::source::reserve_source(&mut columns, 2)?;
407            columns.push((
408                FitField::Lower.into(),
409                DataPayload::Numeric(bounds.lower().clone()),
410            ));
411            columns.push((
412                FitField::Upper.into(),
413                DataPayload::Numeric(bounds.upper().clone()),
414            ));
415        }
416        let relations = crate::data::source::collect_source(
417            (0..predict_x.len()).map(|_| Ok(Some(all_members.clone()))),
418        )?;
419        let fields = StatResult::single_domain(owner, None, columns, relations)?;
420        Ok(FitPredictionRows {
421            x: AxisValues::Numeric(predict_x),
422            fitted: predicted,
423            bounds,
424            fields,
425        })
426    }
427
428    pub(crate) fn scientific_result(
429        &self,
430        source: &crate::builder::PlotDescription,
431        data: crate::data::PlotData<'_, '_>,
432        owner: &ElementRef,
433    ) -> Result<FitResult> {
434        let capture = self.capture.as_ref().expect("actual fitted result capture");
435        let originals = source.primary_layer_data(&owner.declaration());
436        let x = crate::data::select_value(&originals, DataRole::X.into())?;
437        let y = crate::data::select_value(&originals, DataRole::Y.into())?;
438        let raw_x = x.numeric()?;
439        let (observations, leverage) = self.result_observations(source, data, owner, &x, &y)?;
440        let all_members =
441            SourceMembers::from_slots(&[&x, &y], self.alphas.iter().map(|alpha| alpha.slot))?;
442        let predictions = self.result_predictions(owner, raw_x.name(), &all_members)?;
443        let mut domains = observations.domains.clone();
444        domains.extend(predictions.fields.result_domains())?;
445        let (intercept, slope, r_squared) = capture.fit.coefficients();
446        let coefficients = FitCoefficients {
447            keys: Arc::from([RawKey::from("intercept"), RawKey::from("slope")]),
448            values: numeric_column("coefficient", [intercept, slope].into_iter())?,
449        };
450        let terms = crate::data::RawKeyValues::new("term", coefficients.keys.iter().cloned())?;
451        let coefficient_components = vec![
452            DataComponentInfo::scientific("keys", &DataPayload::RawKeys(terms.clone()))?,
453            DataComponentInfo::scientific(
454                "values",
455                &DataPayload::Numeric(coefficients.values.clone()),
456            )?,
457        ];
458        let info = DataDomainInfo::bound(
459            DataDomainRef::scientific(owner, None),
460            terms.len(),
461            None,
462            coefficient_components,
463        )
464        .with_keys(&terms);
465        domains.push_info(
466            info,
467            crate::data::source::collect_source(
468                (0..terms.len()).map(|_| Ok(Some(all_members.clone()))),
469            )?,
470        )?;
471        let diagnostics = FitDiagnostics {
472            rank: 2,
473            df: ExactInteger::from(self.alphas.len() - 2),
474            r_squared,
475            rss: capture.fit.residual_sum_squares(),
476            leverage,
477        };
478        let group = FitGroupResult {
479            owner: owner.clone(),
480            observations,
481            predictions,
482            parameters: FitParameters { coefficients },
483            diagnostics,
484        };
485        Ok(FitResult {
486            groups: Arc::from([group]),
487            domains,
488        })
489    }
490}
491
492crate::orchestrator::science::stat_result_api!(Regression, FitResult, |source, data, layer| {
493    super::PreparedRegression::new(source, data)?
494        .0
495        .scientific_result(source, data, layer)
496});