shrinkage 0.4.0

Composable regularized statistical models in Rust.
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
//! Composition and validated preparation of training problems.

pub mod runtime;
pub use runtime::{
    MatrixDesign, RuntimeDesign, RuntimeMultivariateProblem, RuntimePathProblem, RuntimeProblem,
};

use crate::error::{finite, invalid};
use crate::solver::{ObservedSolver, Solver, SolverObserver, coordinate};
use crate::{Centering, LassoError, LassoFit, Normalization, Preprocessing, Scaling};
pub use crate::{datafit::Gaussian, penalty::L1, solver::CoordinateDescent};
use lazymatrix::{ColumnStats, LazyMatrix, RawColumn, RawColumns};

/// A typed design, datafit, and penalty with training normalization settings.
///
/// [`CoordinateDescent`] supports a borrowed [`RawColumns`] design with
/// [`Gaussian`] and [`L1`], returning [`LassoFit`]. [`crate::ProximalGradient`]
/// uses native forward and transposed products with [`crate::SmoothDatafit`]
/// and a complete [`crate::ProximalPenalty`], returning [`crate::ProximalFit`].
/// Both results retain original-scale parameters and training normalization.
/// [`crate::Irls`] uses column access with [`crate::DiagonalHessianDatafit`] and
/// [`crate::CoordinatePenalty`], returning [`crate::IrlsFit`] with full KKT checks.
/// [`crate::HybridCoordinateDescent`] fits Gaussian [`crate::ClusteredLasso`],
/// [`crate::ChainFusedLasso`], and [`crate::Slope`] with dense aggregates,
/// returning [`crate::HybridFit`] with full PG mapping checks.
/// [`crate::MultivariateGaussian`] with [`crate::AxisPenalty`] uses the same
/// proximal iteration and returns [`crate::MultivariateFit`]. Its coefficient
/// feature and response dimensions and penalty axis are explicit.
///
/// ```
/// # #[cfg(feature = "faer_v0_24")] {
/// use faer::Mat;
/// use shrinkage::{CoordinateDescent, Gaussian, L1, Normalization, Problem};
///
/// let x = Mat::from_fn(3, 1, |i, _| i as f64);
/// let y = [1.0, 3.0, 5.0];
/// let fit = Problem::new(&x, Gaussian::new(&y), L1::new(0.1))
///     .normalize(Normalization::Standardize)
///     .fit_with(&CoordinateDescent::new())?;
/// let predictions = fit.predict(&x)?;
/// # }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug)]
pub struct Problem<X, D, P> {
    design: X,
    datafit: D,
    penalty: P,
    normalization: Normalization,
    supplied_centers: Option<Vec<f64>>,
    supplied_scales: Option<Vec<f64>>,
}

impl<X, D, P> Problem<X, D, P> {
    /// Compose a design, datafit, and penalty.
    pub fn new(design: X, datafit: D, penalty: P) -> Self {
        Self {
            design,
            datafit,
            penalty,
            normalization: Normalization::Auto,
            supplied_centers: None,
            supplied_scales: None,
        }
    }

    /// Borrow the design component.
    pub fn design(&self) -> &X {
        &self.design
    }

    /// Borrow the predictor datafit.
    pub fn datafit(&self) -> &D {
        &self.datafit
    }

    /// Borrow the complete penalty.
    pub fn penalty(&self) -> &P {
        &self.penalty
    }

    /// Selected training normalization policy.
    pub fn normalization(&self) -> Normalization {
        self.normalization
    }

    /// Explicit training centers, if supplied.
    pub fn centers(&self) -> Option<&[f64]> {
        self.supplied_centers.as_deref()
    }

    /// Explicit training scales, if supplied.
    pub fn scales(&self) -> Option<&[f64]> {
        self.supplied_scales.as_deref()
    }

    /// Fit with a solver that supports this composition.
    ///
    /// # Errors
    /// Forwards validation and numerical failures from the selected solver.
    pub fn fit_with<S: Solver<Self>>(&self, solver: &S) -> Result<S::Fit, S::Error> {
        solver.solve(self)
    }

    /// Fit a supported typed problem while observing accepted optimization states.
    ///
    /// Observations use optimization-scale parameters, before back-transformation.
    ///
    /// # Errors
    /// Returns the same validation, numerical, and backend errors as fitting.
    pub fn fit_with_observer<S: ObservedSolver<Self>, O: SolverObserver + ?Sized>(
        &self,
        solver: &S,
        observer: &mut O,
    ) -> Result<S::Fit, S::Error> {
        solver.solve_with_observer(self, observer)
    }

    /// Fit from an explicit optimization-scale point while observing updates.
    ///
    /// # Errors
    /// Forwards fitting errors and rejects invalid initial parameters.
    pub fn fit_from_with_observer<S: ObservedSolver<Self>, O: SolverObserver + ?Sized>(
        &self,
        solver: &S,
        initial: crate::InitialPoint<'_>,
        observer: &mut O,
    ) -> Result<S::Fit, S::Error> {
        solver.solve_from_with_observer(self, Some(initial), observer)
    }

    /// Fit an owned explicit penalty sequence in caller order.
    ///
    /// # Errors
    /// Forwards fitting errors without a partial path. Iteration-limit fits
    /// remain available and initialize the next point.
    pub fn fit_path_with<S, Q>(
        &self,
        solver: &S,
        penalties: Vec<Q>,
    ) -> Result<crate::PathFit<S::Fit, Q>, S::Error>
    where
        S: crate::PathSolver<Self, Q>,
    {
        crate::PathSolver::solve_path(solver, self, penalties)
    }

    /// Generate and fit a regularization sequence with one data preparation.
    ///
    /// # Errors
    /// Forwards invalid options, undefined null models, and fitting errors.
    pub fn fit_regularization_path_with<S: crate::RegularizationPathSolver<Self>>(
        &self,
        solver: &S,
        options: &crate::PathOptions,
    ) -> Result<crate::PathFit<S::Fit, S::Penalty>, S::Error> {
        solver.solve_regularization_path(self, options)
    }

    /// Calculate the zero-coefficient threshold on the optimization scale.
    ///
    /// # Errors
    /// Forwards null-model, component, and backend validation failures.
    pub fn maximum_penalty_with<S: crate::RegularizationPathSolver<Self>>(
        &self,
        solver: &S,
    ) -> Result<crate::PenaltyMaximum, S::Error> {
        solver.maximum_penalty(self)
    }

    /// Select lazy training-column normalization.
    pub fn normalize(mut self, normalization: Normalization) -> Self {
        self.normalization = normalization;
        self
    }

    /// Supply centers in training-column order, checked when fitting.
    pub fn with_centers(mut self, centers: Vec<f64>) -> Self {
        self.supplied_centers = Some(centers);
        self
    }

    /// Supply positive scales in training-column order, checked when fitting.
    pub fn with_scales(mut self, scales: Vec<f64>) -> Self {
        self.supplied_scales = Some(scales);
        self
    }
}

impl<M> Solver<Problem<&M, Gaussian<'_>, L1>> for CoordinateDescent
where
    M: RawColumns<f64> + ColumnStats<f64> + ?Sized,
{
    type Fit = LassoFit;
    type Error = LassoError<M::Error>;

    fn solve(&self, problem: &Problem<&M, Gaussian<'_>, L1>) -> Result<Self::Fit, Self::Error> {
        problem.fit_coordinate(self)
    }
}

impl<M> ObservedSolver<Problem<&M, Gaussian<'_>, L1>> for CoordinateDescent
where
    M: RawColumns<f64> + ColumnStats<f64> + ?Sized,
{
    fn solve_from_with_observer<O: SolverObserver + ?Sized>(
        &self,
        problem: &Problem<&M, Gaussian<'_>, L1>,
        initial: Option<crate::InitialPoint<'_>>,
        observer: &mut O,
    ) -> Result<Self::Fit, Self::Error> {
        problem.fit_coordinate_observed(self, initial, observer)
    }
}

impl<M> Problem<&M, Gaussian<'_>, L1>
where
    M: RawColumns<f64> + ColumnStats<f64> + ?Sized,
{
    fn fit_coordinate(&self, solver: &CoordinateDescent) -> Result<LassoFit, LassoError<M::Error>> {
        self.penalty.validate()?;
        solver.validate(solver.criterion(self.penalty))?;
        self.datafit.validate(self.design.nrows())?;
        let prepared = self.prepare(self.datafit.fit_intercept)?;
        let solution = coordinate::solve(&prepared.matrix, self.datafit, self.penalty, solver)?;
        LassoFit::from_solution(solution, prepared.into_preprocessing())
    }
    fn fit_coordinate_observed<O: SolverObserver + ?Sized>(
        &self,
        solver: &CoordinateDescent,
        initial: Option<crate::InitialPoint<'_>>,
        observer: &mut O,
    ) -> Result<LassoFit, LassoError<M::Error>> {
        self.penalty.validate()?;
        solver.validate(solver.criterion(self.penalty))?;
        self.datafit.validate(self.design.nrows())?;
        let prepared = self.prepare(self.datafit.fit_intercept)?;
        if let Some(initial) = initial {
            initial.validate(prepared.matrix.ncols(), self.datafit.fit_intercept)?;
        }
        let solution = coordinate::solve_observed(
            &prepared.matrix,
            self.datafit,
            self.penalty,
            solver,
            initial,
            observer,
        )?;
        LassoFit::from_solution(solution, prepared.into_preprocessing())
    }
}

impl<M, D, P> Problem<&M, D, P>
where
    M: RawColumns<f64> + ColumnStats<f64> + ?Sized,
{
    pub(crate) fn prepare(
        &self,
        fit_intercept: bool,
    ) -> Result<Prepared<&M>, LassoError<M::Error>> {
        let x = self.design;
        if x.nrows() == 0 {
            return Err(invalid("training data must have at least one observation"));
        }
        validate_matrix(x)?;
        self.prepare_normalization(fit_intercept)
    }
}

impl<M, D, P> Problem<&M, D, P>
where
    M: lazymatrix::MatrixShape + ColumnStats<f64> + ?Sized,
{
    pub(crate) fn prepare_normalization(
        &self,
        fit_intercept: bool,
    ) -> Result<Prepared<&M>, LassoError<M::Error>> {
        prepare_normalization(
            self.design,
            self.normalization,
            self.centers(),
            self.scales(),
            fit_intercept,
        )
    }
}

pub(crate) fn prepare_normalization<'a, M>(
    x: &'a M,
    normalization: Normalization,
    supplied_centers: Option<&[f64]>,
    supplied_scales: Option<&[f64]>,
    fit_intercept: bool,
) -> Result<Prepared<&'a M>, LassoError<M::Error>>
where
    M: lazymatrix::MatrixShape + ColumnStats<f64> + ?Sized,
{
    if x.nrows() == 0 {
        return Err(invalid("training data must have at least one observation"));
    }
    let spec = normalization.specification(fit_intercept);
    validate_supplied(supplied_centers, x.ncols(), false)?;
    validate_supplied(supplied_scales, x.ncols(), true)?;
    let center_rule = if supplied_centers.is_some() {
        Centering::None
    } else {
        spec.center
    };
    let scale_rule = if supplied_scales.is_some() {
        Scaling::None
    } else {
        spec.scale
    };
    let centered_scale = supplied_centers.is_some()
        && matches!(scale_rule, Scaling::L1 | Scaling::L2 | Scaling::MaxAbs);
    let stats_spec = lazymatrix::ColumnNormalization::new(
        center_rule,
        if centered_scale {
            Scaling::None
        } else {
            scale_rule
        },
    );
    let (computed_centers, mut computed_scales) =
        if stats_spec.center != Centering::None || stats_spec.scale != Scaling::None {
            x.normalization_stats(stats_spec)
                .map_err(|source| LassoError::Backend {
                    operation: "computing training normalization statistics",
                    source,
                })?
        } else {
            (None, None)
        };
    if centered_scale {
        let centers = supplied_centers.unwrap();
        computed_scales = Some(
            match scale_rule {
                Scaling::L1 => x.col_l1_centered(centers),
                Scaling::L2 => x.col_l2_centered(centers),
                Scaling::MaxAbs => x.col_maxabs_centered(centers),
                _ => unreachable!(),
            }
            .map_err(|source| LassoError::Backend {
                operation: "computing training normalization statistics",
                source,
            })?,
        );
    }
    let centers = supplied_centers.map(<[f64]>::to_vec).or(computed_centers);
    let mut scales = supplied_scales.map(<[f64]>::to_vec).or(computed_scales);
    validate_statistics(
        &centers,
        x.ncols(),
        supplied_centers.is_some() || spec.center != Centering::None,
        "column centers",
    )?;
    validate_statistics(
        &scales,
        x.ncols(),
        supplied_scales.is_some() || spec.scale != Scaling::None,
        "column scales",
    )?;
    if let Some(scales) = &mut scales {
        for scale in scales {
            if *scale < 0.0 {
                return Err(invalid(
                    "matrix backend returned a negative normalization scale",
                ));
            }
            if *scale == 0.0 {
                *scale = 1.0;
            }
        }
    }
    Ok(Prepared {
        matrix: LazyMatrix::from_column_parts(x, centers, scales),
        spec,
        supplied_centers: supplied_centers.is_some(),
        supplied_scales: supplied_scales.is_some(),
    })
}

pub(crate) struct Prepared<M> {
    pub matrix: LazyMatrix<M>,
    spec: lazymatrix::ColumnNormalization,
    supplied_centers: bool,
    supplied_scales: bool,
}

impl<M: lazymatrix::MatrixShape> Prepared<M> {
    #[cfg(feature = "experimental-block-reader")]
    pub(crate) fn map_data<N: lazymatrix::MatrixShape>(
        self,
        transform: impl FnOnce(M) -> N,
    ) -> Prepared<N> {
        let (matrix, params) = self.matrix.into_parts();
        Prepared {
            matrix: LazyMatrix::from_parts(transform(matrix), params),
            spec: self.spec,
            supplied_centers: self.supplied_centers,
            supplied_scales: self.supplied_scales,
        }
    }

    pub fn into_preprocessing(self) -> Preprocessing {
        let (_, params) = self.matrix.into_parts();
        let (_, centers, scales) = params.into_parts();
        Preprocessing {
            spec: self.spec,
            centers,
            scales,
            supplied_centers: self.supplied_centers,
            supplied_scales: self.supplied_scales,
        }
    }
}

pub(crate) fn validate_matrix<M: RawColumns<f64> + ?Sized, E>(x: &M) -> Result<(), LassoError<E>> {
    for j in 0..x.ncols() {
        let column = x.raw_column(j);
        if column.len() != x.nrows() || column.stored_len() > x.nrows() {
            return Err(invalid(format!(
                "matrix backend returned invalid dimensions for column {j}"
            )));
        }
        let mut valid = true;
        column.for_each_stored(|i, value| {
            valid &= i < x.nrows() && value.is_finite();
        });
        if !valid {
            // Keep error-location tracking out of the valid-input reduction so
            // dense backends can vectorize their finite-value checks.
            let mut invalid_row = None;
            column.for_each_stored(|i, value| {
                if (i >= x.nrows() || !value.is_finite()) && invalid_row.is_none() {
                    invalid_row = Some(i);
                }
            });
            let i = invalid_row.unwrap();
            return Err(invalid(format!(
                "invalid matrix entry at row {i}, column {j}: expected an in-bounds, finite value"
            )));
        }
    }
    Ok(())
}

fn validate_statistics<E>(
    values: &Option<Vec<f64>>,
    ncols: usize,
    expected: bool,
    operation: &'static str,
) -> Result<(), LassoError<E>> {
    if values.is_some() != expected || values.as_ref().is_some_and(|v| v.len() != ncols) {
        return Err(invalid(format!(
            "matrix backend returned unexpected {operation}"
        )));
    }
    if let Some(values) = values {
        for &value in values {
            finite(value, operation, 0)?;
        }
    }
    Ok(())
}

fn validate_supplied<E>(
    values: Option<&[f64]>,
    ncols: usize,
    scales: bool,
) -> Result<(), LassoError<E>> {
    if let Some(values) = values {
        let name = if scales { "scales" } else { "centers" };
        if values.len() != ncols {
            return Err(invalid(format!(
                "supplied {name} length {} does not match {ncols} columns",
                values.len()
            )));
        }
        for (j, &value) in values.iter().enumerate() {
            if !value.is_finite() || (scales && value <= 0.0) {
                return Err(invalid(format!("invalid supplied {name} at column {j}")));
            }
        }
    }
    Ok(())
}