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
// ============================================================================
// Diagnostic Test Helper Functions
// ============================================================================
//! Shared helper functions for diagnostic tests.
//!
//! This module provides utility functions used across multiple diagnostic tests,
//! including:
//!
//! - Data validation (dimension and finite value checks)
//! - P-value computation for common statistical distributions
//! - OLS fitting with numerical stability safeguards
//! - Residual sum of squares calculation
//!
//! # OLS Fitting Strategy
//!
//! The [`fit_ols`] function uses a robust two-stage approach:
//! 1. First attempts standard QR decomposition OLS
//! 2. Falls back to ridge regression (λ = 0.0001) if numerical issues occur
//!
//! This ensures diagnostic tests work correctly even with multicollinear data.
use crate;
use crate;
use crate;
/// Validates regression input data for dimensions and finite values.
///
/// This is a high-performance validation function that checks:
/// 1. All predictor variables have the same length as the response
/// 2. Response variable contains no NaN or infinite values
/// 3. All predictor variables contain no NaN or infinite values
///
/// Uses explicit loops for maximum performance (no closure overhead).
///
/// # Arguments
///
/// * `y` - Response variable (n observations)
/// * `x_vars` - Predictor variables (each expected to have length n)
///
/// # Returns
///
/// `Ok(())` if all validations pass, otherwise an error indicating the specific issue.
///
/// # Errors
///
/// * [`Error::DimensionMismatch`] - if any x_var has different length than y
/// * [`Error::InvalidInput`] - if y or x_vars contain NaN or infinite values
///
/// # Examples
///
/// ```ignore
/// use linreg_core::diagnostics::helpers::validate_regression_data;
///
/// let y = vec![1.0, 2.0, 3.0];
/// let x1 = vec![1.0, 2.0, 3.0];
/// let x2 = vec![2.0, 4.0, 6.0];
///
/// validate_regression_data(&y, &[x1, x2])?;
/// # Ok::<(), linreg_core::Error>(())
/// ```
/// Computes a two-tailed p-value from a t-statistic.
///
/// This function calculates the probability of observing a t-statistic as extreme
/// as the one provided, assuming a two-tailed test. It uses the Student's t
/// cumulative distribution function.
///
/// # Arguments
///
/// * `t` - The t-statistic value
/// * `df` - Degrees of freedom (must be positive)
///
/// # Returns
///
/// The two-tailed p-value in the range `[0, 2]`. For extreme values (`|t| > 100`),
/// returns `0.0` to avoid numerical underflow.
///
/// # Examples
///
/// ```
/// use linreg_core::diagnostics::two_tailed_p_value;
///
/// // t = 2.0 with 10 degrees of freedom
/// let p = two_tailed_p_value(2.0, 10.0);
/// assert!(p > 0.05 && p < 0.10);
/// ```
/// Computes a p-value from an F-statistic.
///
/// Calculates the upper-tail probability of observing an F-statistic as extreme
/// as the one provided, using the Fisher-Snedecor (F) distribution.
///
/// # Arguments
///
/// * `f_stat` - The F-statistic value (must be non-negative)
/// * `df1` - Numerator degrees of freedom
/// * `df2` - Denominator degrees of freedom
///
/// # Returns
///
/// The p-value (upper tail probability) in the range `[0, 1]`. Returns `1.0` for
/// non-positive F-statistics.
///
/// # Examples
///
/// ```
/// use linreg_core::diagnostics::f_p_value;
///
/// // F = 5.0 with df1 = 2, df2 = 10
/// let p = f_p_value(5.0, 2.0, 10.0);
/// assert!(p > 0.0 && p < 0.05);
/// ```
/// Computes a p-value from a chi-squared statistic (upper tail).
///
/// Calculates the probability of observing a chi-squared statistic as extreme
/// as the one provided, using the chi-squared distribution.
///
/// # Arguments
///
/// * `stat` - The chi-squared statistic value (must be non-negative)
/// * `df` - Degrees of freedom
///
/// # Returns
///
/// The upper-tail p-value in the range `[0, 1]`.
///
/// # Examples
///
/// ```ignore
/// use linreg_core::diagnostics::helpers::chi_squared_p_value;
///
/// // chi-squared = 10.0 with df = 5
/// let p = chi_squared_p_value(10.0, 5.0);
/// assert!(p > 0.0 && p < 1.0);
/// ```
/// Computes the residual sum of squares (RSS) from a fitted model.
///
/// The RSS is the sum of squared differences between observed and predicted
/// values: `RSS = Σ(yᵢ - ŷᵢ)²`, where `ŷᵢ = Xᵢβ`.
///
/// This is a measure of model fit - lower values indicate better fit. The RSS
/// is used in many diagnostic tests including the Rainbow test and likelihood
/// ratio tests.
///
/// # Arguments
///
/// * `y` - Observed response values (n observations)
/// * `x` - Design matrix (n × p)
/// * `beta` - Coefficient vector (p elements)
///
/// # Returns
///
/// The residual sum of squares as a non-negative value.
///
/// # Examples
///
/// ```ignore
/// use linreg_core::diagnostics::helpers::compute_rss;
/// use linreg_core::linalg::Matrix;
///
/// let y = vec![2.0, 4.0, 6.0];
/// let x = Matrix::new(3, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0]);
/// let beta = vec![0.0, 2.0]; // y = 2*x
/// let rss = compute_rss(&y, &x, &beta).unwrap();
/// assert_eq!(rss, 0.0); // Perfect fit
/// ```
/// Fits an OLS regression model and returns the coefficient estimates.
///
/// This function provides a robust OLS fitting procedure that first attempts
/// standard QR decomposition, then falls back to ridge regression if numerical
/// instability is detected (e.g., due to multicollinearity).
///
/// The ridge fallback uses a very small regularization parameter (λ = 0.0001)
/// to maintain numerical stability while minimizing distortion of the estimates.
///
/// # Arguments
///
/// * `y` - Response variable (n observations)
/// * `x` - Design matrix (n × p, should include intercept column if needed)
///
/// # Returns
///
/// A vector of coefficient estimates (p elements).
///
/// # Errors
///
/// * [`Error::SingularMatrix`] - if the design matrix is singular and ridge
/// regression also fails
///
/// # Examples
///
/// ```ignore
/// use linreg_core::diagnostics::helpers::fit_ols;
/// use linreg_core::linalg::Matrix;
///
/// let y = vec![2.1, 4.0, 5.9];
/// let x = Matrix::new(3, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0]);
/// let beta = fit_ols(&y, &x).unwrap();
/// assert_eq!(beta.len(), 2); // Intercept and slope
/// ```
/// Standard QR decomposition OLS solver.
///
/// Solves the normal equations using QR decomposition: `Xβ = y`. This is the
/// preferred method for OLS estimation due to its numerical stability.
///
/// The algorithm computes `X = QR` where Q is orthogonal and R is upper
/// triangular, then solves `Rβ = Qᵀy` via back-substitution.
///
/// # Arguments
///
/// * `y` - Response variable (n observations)
/// * `x` - Design matrix (n × p)
///
/// # Returns
///
/// A vector of coefficient estimates (p elements).
///
/// # Errors
///
/// * [`Error::SingularMatrix`] - if the design matrix is singular (p > n or
/// R is not invertible)
/// Ridge regression fallback for multicollinear data.
///
/// Solves the ridge regression problem: `(X'X + λI)β = X'y`. This adds a small
/// positive constant to the diagonal of `X'X`, ensuring invertibility even when
/// the design matrix is rank-deficient.
///
/// Ridge regression is used as a fallback when standard QR decomposition fails
/// due to multicollinearity or numerical singularity.
///
/// # Arguments
///
/// * `y` - Response variable (n observations)
/// * `x` - Design matrix (n × p)
/// * `lambda` - Regularization parameter (small positive value, e.g., 0.0001)
///
/// # Returns
///
/// A vector of ridge-regularized coefficient estimates (p elements).
///
/// # Errors
///
/// * [`Error::SingularMatrix`] - if the ridge-adjusted matrix is still singular