anofox-regression 0.5.7

A robust statistics library for regression analysis
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
//! GLM-specific residual types.
//!
//! Provides Pearson, deviance, and working residuals for generalized linear models.
//!
//! # Residual Types
//!
//! - **Response**: Raw residuals `(y - μ)`
//! - **Pearson**: `(y - μ) / sqrt(V(μ))`
//! - **Deviance**: `sign(y - μ) * sqrt(d_i)` where `d_i` is unit deviance
//! - **Working**: `(y - μ) * (dη/dμ)` - used in IRLS
//!
//! # Reference
//!
//! McCullagh, P. and Nelder, J.A. (1989). Generalized Linear Models, 2nd ed.

use crate::core::GlmFamily;
use faer::Col;

/// Compute response residuals: y - μ.
///
/// The simplest residual type, but variance is not constant.
pub fn response_residuals(y: &Col<f64>, mu: &Col<f64>) -> Col<f64> {
    let n = y.nrows();
    Col::from_fn(n, |i| y[i] - mu[i])
}

/// Compute Pearson residuals: (y - μ) / sqrt(V(μ)).
///
/// Standardized by the variance function, approximately homoscedastic.
pub fn pearson_residuals<F: GlmFamily>(y: &Col<f64>, mu: &Col<f64>, family: &F) -> Col<f64> {
    let n = y.nrows();
    Col::from_fn(n, |i| {
        let v = family.variance(mu[i]);
        if v < 1e-14 {
            0.0
        } else {
            (y[i] - mu[i]) / v.sqrt()
        }
    })
}

/// Compute deviance residuals: sign(y - μ) * sqrt(d_i).
///
/// Each residual contributes d_i² to the total deviance.
/// These residuals have better distributional properties than Pearson residuals.
pub fn deviance_residuals<F: GlmFamily>(y: &Col<f64>, mu: &Col<f64>, family: &F) -> Col<f64> {
    let n = y.nrows();
    Col::from_fn(n, |i| {
        let d_i = family.unit_deviance(y[i], mu[i]);
        let sign = if y[i] >= mu[i] { 1.0 } else { -1.0 };
        sign * d_i.sqrt()
    })
}

/// Compute working residuals: (y - μ) * (dη/dμ).
///
/// Used in the IRLS algorithm. Related to the working response by:
/// z = η + working_residual
pub fn working_residuals<F: GlmFamily>(y: &Col<f64>, mu: &Col<f64>, family: &F) -> Col<f64> {
    let n = y.nrows();
    Col::from_fn(n, |i| {
        let link_deriv = family.link_derivative(mu[i]);
        (y[i] - mu[i]) * link_deriv
    })
}

/// Compute standardized Pearson residuals: r_P / sqrt(φ * (1 - h_ii)).
///
/// Adjusts for both dispersion and leverage.
pub fn standardized_pearson_residuals<F: GlmFamily>(
    y: &Col<f64>,
    mu: &Col<f64>,
    family: &F,
    leverage: &Col<f64>,
    dispersion: f64,
) -> Col<f64> {
    let pearson = pearson_residuals(y, mu, family);
    let n = y.nrows();

    Col::from_fn(n, |i| {
        let h_ii = leverage[i];
        let scale = (dispersion * (1.0 - h_ii)).max(1e-14).sqrt();
        pearson[i] / scale
    })
}

/// Compute standardized deviance residuals: r_D / sqrt(φ * (1 - h_ii)).
///
/// Often preferred over standardized Pearson residuals.
pub fn standardized_deviance_residuals<F: GlmFamily>(
    y: &Col<f64>,
    mu: &Col<f64>,
    family: &F,
    leverage: &Col<f64>,
    dispersion: f64,
) -> Col<f64> {
    let deviance = deviance_residuals(y, mu, family);
    let n = y.nrows();

    Col::from_fn(n, |i| {
        let h_ii = leverage[i];
        let scale = (dispersion * (1.0 - h_ii)).max(1e-14).sqrt();
        deviance[i] / scale
    })
}

/// Compute Pearson's chi-squared statistic: Σ (y - μ)² / V(μ).
///
/// Used for dispersion estimation and goodness-of-fit testing.
pub fn pearson_chi_squared<F: GlmFamily>(y: &[f64], mu: &[f64], family: &F) -> f64 {
    y.iter()
        .zip(mu.iter())
        .map(|(&yi, &mui)| {
            let v = family.variance(mui);
            if v < 1e-14 {
                0.0
            } else {
                (yi - mui).powi(2) / v
            }
        })
        .sum()
}

/// Estimate dispersion parameter φ using Pearson's method.
///
/// φ̂ = X² / (n - p) where X² is Pearson's chi-squared.
pub fn estimate_dispersion_pearson<F: GlmFamily>(
    y: &[f64],
    mu: &[f64],
    family: &F,
    n_params: usize,
) -> f64 {
    let n = y.len();
    if n <= n_params {
        return 1.0;
    }

    let chi_sq = pearson_chi_squared(y, mu, family);
    let df = (n - n_params) as f64;

    chi_sq / df
}

/// Estimate dispersion parameter φ using deviance method.
///
/// φ̂ = D / (n - p) where D is the deviance.
pub fn estimate_dispersion_deviance<F: GlmFamily>(
    y: &[f64],
    mu: &[f64],
    family: &F,
    n_params: usize,
) -> f64 {
    let n = y.len();
    if n <= n_params {
        return 1.0;
    }

    let deviance = family.deviance(y, mu);
    let df = (n - n_params) as f64;

    deviance / df
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{BinomialFamily, TweedieFamily};

    #[test]
    fn test_response_residuals() {
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| (i as f64) + 0.5);

        let resid = response_residuals(&y, &mu);

        for i in 0..5 {
            assert!((resid[i] - (-0.5)).abs() < 1e-10);
        }
    }

    #[test]
    fn test_pearson_residuals_gaussian() {
        let fam = TweedieFamily::gaussian();
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| (i as f64) + 0.5);

        let resid = pearson_residuals(&y, &mu, &fam);

        // For Gaussian, V(μ) = 1, so Pearson = response
        for i in 0..5 {
            assert!((resid[i] - (-0.5)).abs() < 1e-10);
        }
    }

    #[test]
    fn test_pearson_residuals_binomial() {
        let fam = BinomialFamily::logistic();
        let y = Col::from_fn(4, |i| if i < 2 { 0.0 } else { 1.0 });
        let mu = Col::from_fn(4, |_| 0.5);

        let resid = pearson_residuals(&y, &mu, &fam);

        // At μ = 0.5: V(μ) = 0.25, sqrt = 0.5
        // Pearson = (y - 0.5) / 0.5 = ±1
        for i in 0..4 {
            assert!((resid[i].abs() - 1.0).abs() < 1e-10);
        }
    }

    #[test]
    fn test_deviance_residuals_gaussian() {
        let fam = TweedieFamily::gaussian();
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| i as f64 + 0.5);

        let resid = deviance_residuals(&y, &mu, &fam);

        // For Gaussian, unit_deviance = (y-μ)², so deviance residual = y - μ
        for i in 0..5 {
            assert!((resid[i] - (-0.5)).abs() < 1e-10);
        }
    }

    #[test]
    fn test_working_residuals_gaussian() {
        let fam = TweedieFamily::gaussian();
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| i as f64 + 0.5);

        let resid = working_residuals(&y, &mu, &fam);

        // For Gaussian with identity link, dη/dμ = 1, so working = response
        for i in 0..5 {
            assert!((resid[i] - (-0.5)).abs() < 1e-10);
        }
    }

    #[test]
    fn test_pearson_chi_squared() {
        let fam = TweedieFamily::gaussian();
        let y = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let mu = vec![1.0, 2.0, 3.0, 4.0, 5.0];

        // Perfect fit
        let chi_sq = pearson_chi_squared(&y, &mu, &fam);
        assert!(chi_sq < 1e-10);

        // With residuals
        let mu_off = vec![1.5, 2.5, 3.5, 4.5, 5.5];
        let chi_sq = pearson_chi_squared(&y, &mu_off, &fam);
        // Each contributes 0.25, total = 1.25
        assert!((chi_sq - 1.25).abs() < 1e-10);
    }

    #[test]
    fn test_estimate_dispersion() {
        let fam = TweedieFamily::gaussian();
        let y = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let mu = vec![1.2, 2.1, 2.9, 4.0, 5.1];

        let phi = estimate_dispersion_pearson(&y, &mu, &fam, 2);
        // Should be positive
        assert!(phi > 0.0);
    }

    #[test]
    fn test_standardized_residuals() {
        let fam = TweedieFamily::gaussian();
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| i as f64 + 0.5);
        let leverage = Col::from_fn(5, |_| 0.2);
        let dispersion = 1.0;

        let std_resid = standardized_pearson_residuals(&y, &mu, &fam, &leverage, dispersion);

        // Check that residuals are scaled
        let scale = (1.0 * 0.8_f64).sqrt();
        for i in 0..5 {
            assert!((std_resid[i] - (-0.5 / scale)).abs() < 1e-10);
        }
    }

    #[test]
    fn test_standardized_deviance_residuals() {
        let fam = TweedieFamily::gaussian();
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| i as f64 + 0.5);
        let leverage = Col::from_fn(5, |_| 0.2);
        let dispersion = 1.0;

        let std_resid = standardized_deviance_residuals(&y, &mu, &fam, &leverage, dispersion);

        // Check that residuals are scaled
        let scale = (1.0 * 0.8_f64).sqrt();
        for i in 0..5 {
            assert!((std_resid[i] - (-0.5 / scale)).abs() < 1e-10);
        }
    }

    #[test]
    fn test_estimate_dispersion_deviance() {
        let fam = TweedieFamily::gaussian();
        let y = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let mu = vec![1.2, 2.1, 2.9, 4.0, 5.1];

        let phi = estimate_dispersion_deviance(&y, &mu, &fam, 2);
        // Should be positive
        assert!(phi > 0.0);
    }

    #[test]
    fn test_estimate_dispersion_insufficient_data() {
        let fam = TweedieFamily::gaussian();
        let y = vec![1.0, 2.0];
        let mu = vec![1.0, 2.0];

        // n <= n_params should return 1.0
        let phi_pearson = estimate_dispersion_pearson(&y, &mu, &fam, 3);
        assert!((phi_pearson - 1.0).abs() < 1e-10);

        let phi_deviance = estimate_dispersion_deviance(&y, &mu, &fam, 3);
        assert!((phi_deviance - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_pearson_residuals_near_zero_variance() {
        // Use a family where we can get very small variance
        // For Gaussian, V(mu) = 1, so we can't test this branch easily
        // For Poisson, V(mu) = mu, so small mu gives small variance
        // The code returns 0.0 when variance < 1e-14
        use crate::core::{PoissonFamily, PoissonLink};
        let fam = PoissonFamily::new(PoissonLink::Log);
        let y = Col::from_fn(5, |_| 0.0);
        let mu = Col::from_fn(5, |_| 1e-16); // Very small mu, variance = mu < 1e-14

        let resid = pearson_residuals(&y, &mu, &fam);

        // With variance < 1e-14, should return 0.0
        for i in 0..5 {
            assert!(
                (resid[i] - 0.0).abs() < 1e-10,
                "Expected 0.0, got {}",
                resid[i]
            );
        }
    }

    #[test]
    fn test_pearson_chi_squared_near_zero_variance() {
        use crate::core::{PoissonFamily, PoissonLink};
        let fam = PoissonFamily::new(PoissonLink::Log);
        let y = vec![0.0, 0.0, 0.0];
        let mu = vec![1e-16, 1e-16, 1e-16]; // Very small variance < 1e-14

        let chi_sq = pearson_chi_squared(&y, &mu, &fam);
        // Should handle near-zero variance gracefully (returns 0.0 for each term)
        assert!(chi_sq.is_finite());
        assert!((chi_sq - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_standardized_deviance_residuals_high_leverage() {
        let fam = TweedieFamily::gaussian();
        let y = Col::from_fn(5, |i| i as f64);
        let mu = Col::from_fn(5, |i| i as f64 + 0.5);
        // High leverage (close to 1.0 - scale will be clamped)
        let leverage = Col::from_fn(5, |_| 0.99);
        let dispersion = 1.0;

        let std_resid = standardized_deviance_residuals(&y, &mu, &fam, &leverage, dispersion);

        // Residuals should be finite and large due to small scale
        for i in 0..5 {
            assert!(std_resid[i].is_finite());
        }
    }

    #[test]
    fn test_deviance_residuals_binomial() {
        let fam = BinomialFamily::logistic();
        let y = Col::from_fn(4, |i| if i < 2 { 0.0 } else { 1.0 });
        let mu = Col::from_fn(4, |_| 0.5);

        let resid = deviance_residuals(&y, &mu, &fam);

        // All residuals should be finite
        for i in 0..4 {
            assert!(resid[i].is_finite());
        }
        // Sign should match y - mu
        assert!(resid[0] < 0.0); // y=0, mu=0.5
        assert!(resid[2] > 0.0); // y=1, mu=0.5
    }

    #[test]
    fn test_working_residuals_binomial() {
        let fam = BinomialFamily::logistic();
        let y = Col::from_fn(4, |i| if i < 2 { 0.0 } else { 1.0 });
        let mu = Col::from_fn(4, |_| 0.5);

        let resid = working_residuals(&y, &mu, &fam);

        // Working residuals should be finite
        for i in 0..4 {
            assert!(resid[i].is_finite());
        }
    }
}