lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! The owning values of a simple OLS scientific preparation.

use std::sync::Arc;

use crate::{
    data::{
        AxisValues, Bounds, DataComponentInfo, DataDomainInfo, DataDomainRef, DataPayload,
        DataRole, ExactInteger, MemberAddress, RawKey, SourceMembers, SourceRows,
    },
    elements::{ElementRef, LayerSlot},
    layout::PanelPath,
    stats::{
        results::{nullable_column, numeric_column, ResultDomains},
        FitField, StatResult,
    },
    BooleanValues, NumericValues, Result,
};

/// Actual scientific model declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fit {
    /// Simple ordinary least squares with an intercept.
    Ols,
}

impl Fit {
    /// The native simple least-squares model.
    pub const fn ols() -> Self {
        Self::Ols
    }
}

/// Original response representation of a fitted model.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum FitResponse {
    /// Original numeric response.
    Numeric(NumericValues),
}

/// Coefficients in the original predictor/response space.
#[derive(Debug, Clone)]
pub struct FitCoefficients {
    keys: Arc<[RawKey]>,
    values: NumericValues,
}

impl FitCoefficients {
    /// Ordered intercept and predictor term identities.
    pub fn keys(&self) -> &[RawKey] {
        &self.keys
    }
    /// Actual fitted coefficients in the same order.
    pub fn values(&self) -> &NumericValues {
        &self.values
    }
}

/// Model parameters derived by the actual fit.
#[derive(Debug, Clone)]
pub struct FitParameters {
    coefficients: FitCoefficients,
}

impl FitParameters {
    /// Coefficients when the selected model has them.
    pub fn get_coefficients(&self) -> Option<&FitCoefficients> {
        Some(&self.coefficients)
    }
}

/// Owning original observation domain, including non-participating records.
#[derive(Debug, Clone)]
pub struct FitObservationRows {
    original_x: AxisValues,
    original_y: FitResponse,
    used: BooleanValues,
    fitted: NumericValues,
    residual: NumericValues,
    original_slots: Arc<[usize]>,
    source_rows: Option<SourceRows>,
    domains: ResultDomains,
}

impl FitObservationRows {
    /// Original predictor values in logical source order.
    pub fn original_x(&self) -> &AxisValues {
        &self.original_x
    }
    /// Original response, retaining its actual validity.
    pub fn original_y(&self) -> &FitResponse {
        &self.original_y
    }
    /// Whether each original record participated in training.
    pub fn used(&self) -> &BooleanValues {
        &self.used
    }
    /// Actual fitted values on participating observations.
    pub fn fitted(&self) -> &NumericValues {
        &self.fitted
    }
    /// Actual response residuals on participating observations.
    pub fn residual(&self) -> &NumericValues {
        &self.residual
    }
    /// Original bound logical slots, before filtering or faceting.
    pub fn original_slots(&self) -> &[usize] {
        &self.original_slots
    }
    /// Original supplied IDs when explicitly present.
    pub fn source_rows(&self) -> Option<&SourceRows> {
        self.source_rows.as_ref()
    }
    /// Original paired-variable relations in this observation domain.
    pub fn members(&self) -> &[Option<SourceMembers>] {
        self.domains
            .relation(self.domains.infos()[0].reference())
            .expect("actual observation domain")
    }
}

/// Actual prediction grid and its optional mean-response bounds.
#[derive(Debug, Clone)]
pub struct FitPredictionRows {
    x: AxisValues,
    fitted: NumericValues,
    bounds: Option<Bounds>,
    fields: StatResult,
}

impl FitPredictionRows {
    /// Actual original-space prediction coordinates.
    pub fn x(&self) -> &AxisValues {
        &self.x
    }
    /// Actual responses on the prediction grid.
    pub fn fitted(&self) -> &NumericValues {
        &self.fitted
    }
    /// Actual optional interval endpoints, without generating new predictions.
    pub fn bounds(&self) -> Option<&Bounds> {
        self.bounds.as_ref()
    }
    /// Original training members of the actual prediction domain.
    pub fn members(&self) -> &[Option<SourceMembers>] {
        self.fields
            .get_members(FitField::X)
            .expect("actual prediction domain")
    }
}

/// Diagnostics available from the fitted simple OLS model.
#[derive(Debug, Clone)]
pub struct FitDiagnostics {
    rank: usize,
    df: ExactInteger,
    r_squared: f64,
    rss: Option<f64>,
    leverage: NumericValues,
}

impl FitDiagnostics {
    /// Actual design rank.
    pub fn rank(&self) -> Option<usize> {
        Some(self.rank)
    }
    /// Exact residual degrees of freedom.
    pub fn df(&self) -> Option<&ExactInteger> {
        Some(&self.df)
    }
    /// Actual coefficient of determination.
    pub fn r_squared(&self) -> f64 {
        self.r_squared
    }
    /// Residual sum of squares, when representable in the original response space.
    pub fn residual_sum_squares(&self) -> Option<f64> {
        self.rss
    }
    /// Actual leverage values on participating training observations.
    pub fn get_leverage(&self) -> Option<&NumericValues> {
        Some(&self.leverage)
    }
}

/// The actual model values for one panel and training group.
#[derive(Debug, Clone)]
pub struct FitGroupResult {
    owner: ElementRef,
    observations: FitObservationRows,
    predictions: FitPredictionRows,
    parameters: FitParameters,
    diagnostics: FitDiagnostics,
}

impl FitGroupResult {
    /// Actual scientific panel.
    pub fn panel(&self) -> &PanelPath {
        self.owner.panel()
    }
    /// Actual declaring layer.
    pub fn layer_slot(&self) -> LayerSlot {
        self.owner.layer_slot()
    }
    /// Actual group key, absent for the current ungrouped OLS model.
    pub const fn group_key(&self) -> Option<&crate::data::GroupKey> {
        None
    }
    /// Original observation domain.
    pub fn observations(&self) -> &FitObservationRows {
        &self.observations
    }
    /// Actual independent prediction domain.
    pub fn predictions(&self) -> &FitPredictionRows {
        &self.predictions
    }
    /// Actual fitted parameters.
    pub fn parameters(&self) -> &FitParameters {
        &self.parameters
    }
    /// Actual available diagnostics.
    pub fn diagnostics(&self) -> &FitDiagnostics {
        &self.diagnostics
    }
}

/// A complete owning native fit from one scientific preparation.
#[derive(Debug, Clone)]
pub struct FitResult {
    groups: Arc<[FitGroupResult]>,
    domains: ResultDomains,
}

impl FitResult {
    /// Model used in this preparation.
    pub const fn get_model(&self) -> Fit {
        Fit::Ols
    }
    /// Actual training groups.
    pub fn groups(&self) -> &[FitGroupResult] {
        &self.groups
    }
    /// Shared actual prediction fields, not a second fit.
    pub fn stat_fields(&self) -> &StatResult {
        &self.groups[0].predictions.fields
    }
    /// Actual observation and prediction domains.
    pub fn domains(&self) -> &[DataDomainInfo] {
        self.domains.infos()
    }
    /// Read a member of an actual result domain.
    pub fn members_in(
        &self,
        domain: &DataDomainRef,
        address: impl Into<MemberAddress>,
    ) -> Result<Option<SourceMembers>> {
        self.domains.members_in(domain, &address.into())
    }
    /// Read a member when the result has a single actual domain.
    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
        self.domains.members(&address.into())
    }
}

fn finite(value: f64) -> Option<f64> {
    value.is_finite().then_some(value)
}

impl super::PreparedRegression {
    fn result_observations(
        &self,
        source: &crate::builder::PlotDescription,
        data: crate::data::PlotData<'_, '_>,
        owner: &ElementRef,
        x: &crate::data::DataValue,
        y: &crate::data::DataValue,
    ) -> Result<(FitObservationRows, NumericValues)> {
        let capture = self.capture.as_ref().expect("actual captured fit");
        let raw_x = x.numeric()?;
        let raw_y = y.numeric()?;
        let original_slots = crate::data::source::collect_source(
            (0..data.height()).map(|row| Ok(data.row_index(row))),
        )?;
        let training = [x, y];
        let observations_members = crate::data::source::collect_source(
            original_slots
                .iter()
                .map(|&slot| Ok(Some(SourceMembers::from_slots(&training, [slot])?))),
        )?;
        let source_rows = source
            .source_row_map()
            .map(|rows| {
                SourceRows::new(
                    original_slots
                        .iter()
                        .map(|&slot| rows.get(slot).expect("actual original ID")),
                )
            })
            .transpose()?;

        // The admitted OLS rows are retained in source order. The native fit's
        // observation values come from its original residual pass.
        let mut used_values = Vec::new();
        let mut fitted_values = Vec::new();
        let mut residual_values = Vec::new();
        let mut leverage_values = Vec::new();
        for values in [
            &mut fitted_values,
            &mut residual_values,
            &mut leverage_values,
        ] {
            crate::data::source::reserve_source(values, original_slots.len())?;
        }
        crate::data::source::reserve_source(&mut used_values, original_slots.len())?;
        for &slot in &original_slots {
            crate::operation::work(1)?;
            let index = self
                .alphas
                .binary_search_by_key(&slot, |alpha| alpha.slot)
                .ok();
            let observation =
                index.map(|at| &capture.fit.observations().expect("actual diagnostics")[at]);
            used_values.push(index.is_some());
            fitted_values.push(observation.and_then(|value| finite(value.fitted)));
            residual_values.push(observation.and_then(|value| finite(value.residual)));
            leverage_values.push(observation.and_then(|value| finite(value.leverage)));
        }
        crate::operation::memory(used_values.len() as u128 * std::mem::size_of::<bool>() as u128)?;
        let used = BooleanValues::new("used", used_values);
        let fitted = nullable_column("fitted", fitted_values.into_iter())?;
        let residual = nullable_column("residual", residual_values.into_iter())?;
        let leverage = nullable_column("leverage", leverage_values.into_iter())?;
        // Own the same original values, including present NaN and null.
        crate::operation::memory(
            original_slots.len() as u128
                * 2
                * (std::mem::size_of::<f64>() + std::mem::size_of::<Option<f64>>()) as u128,
        )?;
        let original_x = raw_x.select(&original_slots)?;
        let original_y = raw_y.select(&original_slots)?;
        let mut domains = ResultDomains::default();
        let components = crate::data::source::collect_source(
            [
                ("original_x", DataPayload::Numeric(original_x.clone())),
                ("original_y", DataPayload::Numeric(original_y.clone())),
                ("used", DataPayload::Boolean(used.clone())),
                ("fitted", DataPayload::Numeric(fitted.clone())),
                ("residual", DataPayload::Numeric(residual.clone())),
                ("leverage", DataPayload::Numeric(leverage.clone())),
            ]
            .into_iter()
            .map(|(name, values)| {
                DataComponentInfo::scientific_with_members(name, &values, &observations_members)
            }),
        )?;
        domains.push_info(
            DataDomainInfo::bound(
                DataDomainRef::scientific(owner, None),
                original_slots.len(),
                source_rows.as_ref(),
                components,
            ),
            observations_members,
        )?;
        Ok((
            FitObservationRows {
                original_x: AxisValues::Numeric(original_x),
                original_y: FitResponse::Numeric(original_y),
                used,
                fitted,
                residual,
                original_slots: original_slots.into(),
                source_rows,
                domains,
            },
            leverage,
        ))
    }

    fn result_predictions(
        &self,
        owner: &ElementRef,
        predictor_name: &str,
        all_members: &SourceMembers,
    ) -> Result<FitPredictionRows> {
        let capture = self.capture.as_ref().expect("actual captured fit");
        let (predict_x, predicted, bounds) = if let Some(values) = &self.band_values {
            (
                numeric_column(predictor_name, values.iter().map(|v| v.0))?,
                numeric_column("fitted", capture.predicted.iter().copied())?,
                Some(Bounds::new(
                    numeric_column("lower", values.iter().map(|v| v.1))?,
                    numeric_column("upper", values.iter().map(|v| v.2))?,
                )),
            )
        } else {
            (
                numeric_column(predictor_name, self.fit_line.iter().map(|v| v.0))?,
                numeric_column("fitted", self.fit_line.iter().map(|v| v.1))?,
                None,
            )
        };
        let mut columns = vec![
            (FitField::X.into(), DataPayload::Numeric(predict_x.clone())),
            (
                FitField::Fitted.into(),
                DataPayload::Numeric(predicted.clone()),
            ),
        ];
        if let Some(bounds) = &bounds {
            crate::data::source::reserve_source(&mut columns, 2)?;
            columns.push((
                FitField::Lower.into(),
                DataPayload::Numeric(bounds.lower().clone()),
            ));
            columns.push((
                FitField::Upper.into(),
                DataPayload::Numeric(bounds.upper().clone()),
            ));
        }
        let relations = crate::data::source::collect_source(
            (0..predict_x.len()).map(|_| Ok(Some(all_members.clone()))),
        )?;
        let fields = StatResult::single_domain(owner, None, columns, relations)?;
        Ok(FitPredictionRows {
            x: AxisValues::Numeric(predict_x),
            fitted: predicted,
            bounds,
            fields,
        })
    }

    pub(crate) fn scientific_result(
        &self,
        source: &crate::builder::PlotDescription,
        data: crate::data::PlotData<'_, '_>,
        owner: &ElementRef,
    ) -> Result<FitResult> {
        let capture = self.capture.as_ref().expect("actual fitted result capture");
        let originals = source.primary_layer_data(&owner.declaration());
        let x = crate::data::select_value(&originals, DataRole::X.into())?;
        let y = crate::data::select_value(&originals, DataRole::Y.into())?;
        let raw_x = x.numeric()?;
        let (observations, leverage) = self.result_observations(source, data, owner, &x, &y)?;
        let all_members =
            SourceMembers::from_slots(&[&x, &y], self.alphas.iter().map(|alpha| alpha.slot))?;
        let predictions = self.result_predictions(owner, raw_x.name(), &all_members)?;
        let mut domains = observations.domains.clone();
        domains.extend(predictions.fields.result_domains())?;
        let (intercept, slope, r_squared) = capture.fit.coefficients();
        let coefficients = FitCoefficients {
            keys: Arc::from([RawKey::from("intercept"), RawKey::from("slope")]),
            values: numeric_column("coefficient", [intercept, slope].into_iter())?,
        };
        let terms = crate::data::RawKeyValues::new("term", coefficients.keys.iter().cloned())?;
        let coefficient_components = vec![
            DataComponentInfo::scientific("keys", &DataPayload::RawKeys(terms.clone()))?,
            DataComponentInfo::scientific(
                "values",
                &DataPayload::Numeric(coefficients.values.clone()),
            )?,
        ];
        let info = DataDomainInfo::bound(
            DataDomainRef::scientific(owner, None),
            terms.len(),
            None,
            coefficient_components,
        )
        .with_keys(&terms);
        domains.push_info(
            info,
            crate::data::source::collect_source(
                (0..terms.len()).map(|_| Ok(Some(all_members.clone()))),
            )?,
        )?;
        let diagnostics = FitDiagnostics {
            rank: 2,
            df: ExactInteger::from(self.alphas.len() - 2),
            r_squared,
            rss: capture.fit.residual_sum_squares(),
            leverage,
        };
        let group = FitGroupResult {
            owner: owner.clone(),
            observations,
            predictions,
            parameters: FitParameters { coefficients },
            diagnostics,
        };
        Ok(FitResult {
            groups: Arc::from([group]),
            domains,
        })
    }
}

crate::orchestrator::science::stat_result_api!(Regression, FitResult, |source, data, layer| {
    super::PreparedRegression::new(source, data)?
        .0
        .scientific_result(source, data, layer)
});