linreg_core/
core.rs

1//! Core OLS regression implementation.
2//!
3//! This module provides the main Ordinary Least Squares regression functionality
4//! that can be used directly in Rust code. Functions accept native Rust slices
5//! and return Result types for proper error handling.
6//!
7//! # Example
8//!
9//! ```
10//! # use linreg_core::core::ols_regression;
11//! # use linreg_core::Error;
12//! let y = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
13//! let x1 = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
14//! let x2 = vec![2.0, 3.0, 3.5, 4.0, 4.5, 5.0];
15//! let names = vec![
16//!     "Intercept".to_string(),
17//!     "X1".to_string(),
18//!     "X2".to_string(),
19//! ];
20//!
21//! let result = ols_regression(&y, &[x1, x2], &names)?;
22//! # Ok::<(), Error>(())
23//! ```
24
25use crate::distributions::{fisher_snedecor_cdf, student_t_cdf, student_t_inverse_cdf};
26use crate::error::{Error, Result};
27use crate::linalg::{vec_dot, vec_mean, vec_sub, Matrix};
28use serde::Serialize;
29
30// ============================================================================
31// Numerical Constants
32// ============================================================================
33
34/// Minimum threshold for standardized residual denominator to avoid division by zero.
35/// When (1 - leverage) is very small, the observation has extremely high leverage
36/// and standardized residuals may be unreliable.
37const MIN_LEVERAGE_DENOM: f64 = 1e-10;
38
39// ============================================================================
40// Result Types
41// ============================================================================
42//
43// Structs containing the output of regression computations.
44
45/// Result of VIF (Variance Inflation Factor) calculation.
46///
47/// VIF measures how much the variance of an estimated regression coefficient
48/// increases due to multicollinearity among the predictors.
49///
50/// # Fields
51///
52/// * `variable` - Name of the predictor variable
53/// * `vif` - Variance Inflation Factor (VIF > 10 indicates high multicollinearity)
54/// * `rsquared` - R-squared from regressing this predictor on all others
55/// * `interpretation` - Human-readable interpretation of the VIF value
56///
57/// # Example
58///
59/// ```
60/// # use linreg_core::core::VifResult;
61/// let vif = VifResult {
62///     variable: "X1".to_string(),
63///     vif: 2.5,
64///     rsquared: 0.6,
65///     interpretation: "Low multicollinearity".to_string(),
66/// };
67/// assert_eq!(vif.variable, "X1");
68/// ```
69#[derive(Debug, Clone, Serialize)]
70pub struct VifResult {
71    /// Name of the predictor variable
72    pub variable: String,
73    /// Variance Inflation Factor (VIF > 10 indicates high multicollinearity)
74    pub vif: f64,
75    /// R-squared from regressing this predictor on all others
76    pub rsquared: f64,
77    /// Human-readable interpretation of the VIF value
78    pub interpretation: String,
79}
80
81/// Complete output from OLS regression.
82///
83/// Contains all coefficients, statistics, diagnostics, and residuals from
84/// an Ordinary Least Squares regression.
85///
86/// # Example
87///
88/// ```
89/// # use linreg_core::core::ols_regression;
90/// let y = vec![1.0, 2.0, 3.0, 4.0, 5.0];
91/// let x1 = vec![1.0, 2.0, 3.0, 4.0, 5.0];
92/// let names = vec!["Intercept".to_string(), "X1".to_string()];
93///
94/// let result = ols_regression(&y, &[x1], &names).unwrap();
95/// assert!(result.r_squared > 0.0);
96/// assert_eq!(result.coefficients.len(), 2); // intercept + 1 predictor
97/// ```
98#[derive(Debug, Clone, Serialize)]
99pub struct RegressionOutput {
100    /// Regression coefficients (including intercept)
101    pub coefficients: Vec<f64>,
102    /// Standard errors of coefficients
103    pub std_errors: Vec<f64>,
104    /// t-statistics for coefficient significance tests
105    pub t_stats: Vec<f64>,
106    /// Two-tailed p-values for coefficients
107    pub p_values: Vec<f64>,
108    /// Lower bounds of 95% confidence intervals
109    pub conf_int_lower: Vec<f64>,
110    /// Upper bounds of 95% confidence intervals
111    pub conf_int_upper: Vec<f64>,
112    /// R-squared (coefficient of determination)
113    pub r_squared: f64,
114    /// Adjusted R-squared (accounts for number of predictors)
115    pub adj_r_squared: f64,
116    /// F-statistic for overall model significance
117    pub f_statistic: f64,
118    /// P-value for F-statistic
119    pub f_p_value: f64,
120    /// Mean squared error of residuals
121    pub mse: f64,
122    /// Root mean squared error (prediction error in original units)
123    pub rmse: f64,
124    /// Mean absolute error of residuals
125    pub mae: f64,
126    /// Standard error of the regression (residual standard deviation)
127    pub std_error: f64,
128    /// Raw residuals (observed - predicted)
129    pub residuals: Vec<f64>,
130    /// Standardized residuals (accounting for leverage)
131    pub standardized_residuals: Vec<f64>,
132    /// Fitted/predicted values
133    pub predictions: Vec<f64>,
134    /// Leverage values for each observation (diagonal of hat matrix)
135    pub leverage: Vec<f64>,
136    /// Variance Inflation Factors for detecting multicollinearity
137    pub vif: Vec<VifResult>,
138    /// Number of observations
139    pub n: usize,
140    /// Number of predictor variables (excluding intercept)
141    pub k: usize,
142    /// Degrees of freedom for residuals (n - k - 1)
143    pub df: usize,
144    /// Names of variables (including intercept)
145    pub variable_names: Vec<String>,
146}
147
148// ============================================================================
149// Statistical Helper Functions
150// ============================================================================
151//
152// Utility functions for computing p-values, critical values, and leverage.
153
154/// Computes a two-tailed p-value from a t-statistic.
155///
156/// Uses the Student's t-distribution CDF to calculate the probability
157/// of observing a t-statistic as extreme as the one provided.
158///
159/// # Arguments
160///
161/// * `t` - The t-statistic value
162/// * `df` - Degrees of freedom
163///
164/// # Example
165///
166/// ```
167/// # use linreg_core::core::two_tailed_p_value;
168/// let p = two_tailed_p_value(2.0, 20.0);
169/// assert!(p > 0.0 && p < 0.1);
170/// ```
171pub fn two_tailed_p_value(t: f64, df: f64) -> f64 {
172    if t.abs() > 100.0 {
173        return 0.0;
174    }
175
176    let cdf = student_t_cdf(t, df);
177    if t >= 0.0 {
178        2.0 * (1.0 - cdf)
179    } else {
180        2.0 * cdf
181    }
182}
183
184/// Computes the critical t-value for a given significance level and degrees of freedom.
185///
186/// Returns the t-value such that the area under the t-distribution curve
187/// to the right of it equals alpha/2 (two-tailed test).
188///
189/// # Arguments
190///
191/// * `df` - Degrees of freedom
192/// * `alpha` - Significance level (typically 0.05 for 95% confidence)
193///
194/// # Example
195///
196/// ```
197/// # use linreg_core::core::t_critical_quantile;
198/// let t_crit = t_critical_quantile(20.0, 0.05);
199/// assert!(t_crit > 2.0); // approximately 2.086 for df=20, alpha=0.05
200/// ```
201pub fn t_critical_quantile(df: f64, alpha: f64) -> f64 {
202    let p = 1.0 - alpha / 2.0;
203    student_t_inverse_cdf(p, df)
204}
205
206/// Computes a p-value from an F-statistic.
207///
208/// Uses the F-distribution CDF to calculate the probability of observing
209/// an F-statistic as extreme as the one provided.
210///
211/// # Arguments
212///
213/// * `f_stat` - The F-statistic value
214/// * `df1` - Numerator degrees of freedom
215/// * `df2` - Denominator degrees of freedom
216///
217/// # Example
218///
219/// ```
220/// # use linreg_core::core::f_p_value;
221/// let p = f_p_value(5.0, 2.0, 20.0);
222/// assert!(p > 0.0 && p < 0.05);
223/// ```
224pub fn f_p_value(f_stat: f64, df1: f64, df2: f64) -> f64 {
225    if f_stat <= 0.0 {
226        return 1.0;
227    }
228    1.0 - fisher_snedecor_cdf(f_stat, df1, df2)
229}
230
231/// Computes leverage values from the design matrix and its inverse.
232///
233/// Leverage measures how far an observation's predictor values are from
234/// the center of the predictor space. High leverage points can have
235/// disproportionate influence on the regression results.
236///
237/// # Arguments
238///
239/// * `x` - Design matrix (including intercept column)
240/// * `xtx_inv` - Inverse of X'X matrix
241#[allow(clippy::needless_range_loop)]
242pub fn compute_leverage(x: &Matrix, xtx_inv: &Matrix) -> Vec<f64> {
243    let n = x.rows;
244    let mut leverage = vec![0.0; n];
245    for i in 0..n {
246        // x_row is (1, cols)
247        // temp = x_row * xtx_inv (1, cols)
248        // lev = temp * x_row^T (1, 1)
249
250        // Manual row extraction and multiplication
251        let mut row_vec = vec![0.0; x.cols];
252        for j in 0..x.cols {
253            row_vec[j] = x.get(i, j);
254        }
255
256        let mut temp_vec = vec![0.0; x.cols];
257        for c in 0..x.cols {
258            let mut sum = 0.0;
259            for k in 0..x.cols {
260                sum += row_vec[k] * xtx_inv.get(k, c);
261            }
262            temp_vec[c] = sum;
263        }
264
265        leverage[i] = vec_dot(&temp_vec, &row_vec);
266    }
267    leverage
268}
269
270// ============================================================================
271// VIF Calculation
272// ============================================================================
273//
274// Variance Inflation Factor analysis for detecting multicollinearity.
275
276/// Calculates Variance Inflation Factors for all predictors.
277///
278/// VIF quantifies the severity of multicollinearity in a regression analysis.
279/// A VIF > 10 indicates high multicollinearity that may need to be addressed.
280///
281/// # Arguments
282///
283/// * `x_vars` - Predictor variables (each of length n)
284/// * `names` - Variable names (including intercept as first element)
285/// * `n` - Number of observations
286///
287/// # Returns
288///
289/// Vector of VIF results for each predictor (excluding intercept).
290///
291/// # Example
292///
293/// ```
294/// # use linreg_core::core::calculate_vif;
295/// let x1 = vec![1.0, 2.0, 3.0, 4.0, 5.0];
296/// let x2 = vec![2.0, 4.0, 6.0, 8.0, 10.0];
297/// let names = vec!["Intercept".to_string(), "X1".to_string(), "X2".to_string()];
298///
299/// let vif_results = calculate_vif(&[x1, x2], &names, 5);
300/// assert_eq!(vif_results.len(), 2);
301/// // Perfectly collinear variables will have VIF = infinity
302/// ```
303pub fn calculate_vif(x_vars: &[Vec<f64>], names: &[String], n: usize) -> Vec<VifResult> {
304    let k = x_vars.len();
305    if k <= 1 {
306        return vec![];
307    }
308
309    // Standardize predictors (Z-score)
310    let mut z_data = vec![0.0; n * k];
311
312    for (j, var) in x_vars.iter().enumerate() {
313        let mean = vec_mean(var);
314        let variance = var.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / ((n - 1) as f64);
315        let std_dev = variance.sqrt();
316
317        // Handle constant variables
318        if std_dev.abs() < 1e-10 {
319            return names
320                .iter()
321                .skip(1)
322                .map(|name| VifResult {
323                    variable: name.clone(),
324                    vif: f64::INFINITY,
325                    rsquared: 1.0,
326                    interpretation: "Constant variable (undefined correlation)".to_string(),
327                })
328                .collect();
329        }
330
331        for i in 0..n {
332            z_data[i * k + j] = (var[i] - mean) / std_dev;
333        }
334    }
335
336    let z = Matrix::new(n, k, z_data);
337
338    // Correlation Matrix R = (1/(n-1)) * Z^T * Z
339    let z_t = z.transpose();
340    let zt_z = z_t.matmul(&z);
341
342    // Scale by 1/(n-1)
343    let mut r_corr = zt_z; // Copy
344    let factor = 1.0 / ((n - 1) as f64);
345    for val in &mut r_corr.data {
346        *val *= factor;
347    }
348
349    // Invert R using QR on R_corr (since it's symmetric positive definite, Cholesky is better but QR works)
350    // Or just generic inversion. We implemented generic inversion for Upper Triangular.
351    // Let's use QR: A = QR => A^-1 = R^-1 Q^T
352    let (q_corr, r_corr_tri) = r_corr.qr();
353
354    let r_inv_opt = r_corr_tri.invert_upper_triangular();
355
356    let r_inv = match r_inv_opt {
357        Some(inv) => inv.matmul(&q_corr.transpose()),
358        None => {
359            return names
360                .iter()
361                .skip(1)
362                .map(|name| VifResult {
363                    variable: name.clone(),
364                    vif: f64::INFINITY,
365                    rsquared: 1.0,
366                    interpretation: "Perfect multicollinearity (singular matrix)".to_string(),
367                })
368                .collect();
369        },
370    };
371
372    // Extract diagonals
373    let mut results = vec![];
374    for j in 0..k {
375        let vif = r_inv.get(j, j);
376        let vif = if vif < 1.0 { 1.0 } else { vif };
377        let rsquared = 1.0 - 1.0 / vif;
378
379        let interpretation = if vif.is_infinite() {
380            "Perfect multicollinearity".to_string()
381        } else if vif > 10.0 {
382            "High multicollinearity - consider removing".to_string()
383        } else if vif > 5.0 {
384            "Moderate multicollinearity".to_string()
385        } else {
386            "Low multicollinearity".to_string()
387        };
388
389        results.push(VifResult {
390            variable: names[j + 1].clone(),
391            vif,
392            rsquared,
393            interpretation,
394        });
395    }
396
397    results
398}
399
400// ============================================================================
401// OLS Regression
402// ============================================================================
403//
404// Ordinary Least Squares regression implementation using QR decomposition.
405
406/// Performs Ordinary Least Squares regression using QR decomposition.
407///
408/// Uses a numerically stable QR decomposition approach to solve the normal
409/// equations. Returns comprehensive statistics including coefficients,
410/// standard errors, t-statistics, p-values, and diagnostic measures.
411///
412/// # Arguments
413///
414/// * `y` - Response variable (n observations)
415/// * `x_vars` - Predictor variables (each of length n)
416/// * `variable_names` - Names for variables (including intercept)
417///
418/// # Returns
419///
420/// A [`RegressionOutput`] containing all regression statistics and diagnostics.
421///
422/// # Errors
423///
424/// Returns [`Error::InsufficientData`] if n ≤ k + 1.
425/// Returns [`Error::SingularMatrix`] if perfect multicollinearity exists.
426/// Returns [`Error::InvalidInput`] if coefficients are NaN.
427///
428/// # Example
429///
430/// ```
431/// # use linreg_core::core::ols_regression;
432/// # use linreg_core::Error;
433/// let y = vec![2.5, 3.7, 4.2, 5.1, 6.3, 7.0];
434/// let x1 = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
435/// let x2 = vec![2.0, 4.0, 5.0, 4.0, 3.0, 2.0];
436/// let names = vec![
437///     "Intercept".to_string(),
438///     "Temperature".to_string(),
439///     "Pressure".to_string(),
440/// ];
441///
442/// let result = ols_regression(&y, &[x1, x2], &names)?;
443/// println!("R-squared: {}", result.r_squared);
444/// # Ok::<(), Error>(())
445/// ```
446#[allow(clippy::needless_range_loop)]
447pub fn ols_regression(
448    y: &[f64],
449    x_vars: &[Vec<f64>],
450    variable_names: &[String],
451) -> Result<RegressionOutput> {
452    let n = y.len();
453    let k = x_vars.len();
454    let p = k + 1;
455
456    // Validate inputs
457    if n <= k + 1 {
458        return Err(Error::InsufficientData {
459            required: k + 2,
460            available: n,
461        });
462    }
463
464    // Validate dimensions and finite values using shared helper
465    crate::diagnostics::validate_regression_data(y, x_vars)?;
466
467    // Prepare variable names
468    let mut names = variable_names.to_vec();
469    while names.len() <= k {
470        names.push(format!("X{}", names.len()));
471    }
472
473    // Create design matrix
474    let mut x_data = vec![0.0; n * p];
475    for (row, _yi) in y.iter().enumerate() {
476        x_data[row * p] = 1.0; // intercept
477        for (col, x_var) in x_vars.iter().enumerate() {
478            x_data[row * p + col + 1] = x_var[row];
479        }
480    }
481
482    let x_matrix = Matrix::new(n, p, x_data);
483
484    // QR Decomposition
485    let (q, r) = x_matrix.qr();
486
487    // Solve R * beta = Q^T * y
488    // extract upper p x p part of R
489    let mut r_upper = Matrix::zeros(p, p);
490    for i in 0..p {
491        for j in 0..p {
492            r_upper.set(i, j, r.get(i, j));
493        }
494    }
495
496    // Q^T * y
497    let q_t = q.transpose();
498    let qty = q_t.mul_vec(y);
499
500    // Take first p elements of qty
501    let rhs_vec = qty[0..p].to_vec();
502    let rhs_mat = Matrix::new(p, 1, rhs_vec); // column vector
503
504    // Invert R_upper
505    let r_inv = match r_upper.invert_upper_triangular() {
506        Some(inv) => inv,
507        None => return Err(Error::SingularMatrix),
508    };
509
510    let beta_mat = r_inv.matmul(&rhs_mat);
511    let beta = beta_mat.data;
512
513    // Validate coefficients
514    if beta.iter().any(|&b| b.is_nan()) {
515        return Err(Error::InvalidInput("Coefficients contain NaN".to_string()));
516    }
517
518    // Compute predictions and residuals
519    let predictions = x_matrix.mul_vec(&beta);
520    let residuals = vec_sub(y, &predictions);
521
522    // Compute sums of squares
523    let y_mean = vec_mean(y);
524    let ss_total: f64 = y.iter().map(|&yi| (yi - y_mean).powi(2)).sum();
525    let ss_residual: f64 = residuals.iter().map(|&r| r.powi(2)).sum();
526    let ss_regression = ss_total - ss_residual;
527
528    // R-squared and adjusted R-squared
529    let r_squared = if ss_total == 0.0 {
530        f64::NAN
531    } else {
532        1.0 - ss_residual / ss_total
533    };
534
535    let adj_r_squared = if ss_total == 0.0 {
536        f64::NAN
537    } else {
538        1.0 - (1.0 - r_squared) * ((n - 1) as f64 / (n - k - 1) as f64)
539    };
540
541    // Mean squared error and standard error
542    let df = n - k - 1;
543    let mse = ss_residual / df as f64;
544    let std_error = mse.sqrt();
545
546    // Standard errors using (X'X)^-1 = R^-1 (R')^-1
547    // xtx_inv = r_inv * r_inv^T
548    let xtx_inv = r_inv.matmul(&r_inv.transpose());
549
550    let mut std_errors = vec![0.0; k + 1];
551    for i in 0..=k {
552        std_errors[i] = (xtx_inv.get(i, i) * mse).sqrt();
553        if std_errors[i].is_nan() {
554            return Err(Error::InvalidInput(format!(
555                "Standard error for coefficient {} is NaN",
556                i
557            )));
558        }
559    }
560
561    // T-statistics and p-values
562    let t_stats: Vec<f64> = beta
563        .iter()
564        .zip(&std_errors)
565        .map(|(&b, &se)| b / se)
566        .collect();
567    let p_values: Vec<f64> = t_stats
568        .iter()
569        .map(|&t| two_tailed_p_value(t, df as f64))
570        .collect();
571
572    // Confidence intervals
573    let alpha = 0.05;
574    let t_critical = t_critical_quantile(df as f64, alpha);
575
576    let conf_int_lower: Vec<f64> = beta
577        .iter()
578        .zip(&std_errors)
579        .map(|(&b, &se)| b - t_critical * se)
580        .collect();
581    let conf_int_upper: Vec<f64> = beta
582        .iter()
583        .zip(&std_errors)
584        .map(|(&b, &se)| b + t_critical * se)
585        .collect();
586
587    // Leverage
588    let leverage = compute_leverage(&x_matrix, &xtx_inv);
589
590    // Standardized residuals
591    let residuals_vec = residuals.clone();
592    let standardized_residuals: Vec<f64> = residuals_vec
593        .iter()
594        .zip(&leverage)
595        .map(|(&r, &h)| {
596            let factor = (1.0 - h).max(MIN_LEVERAGE_DENOM).sqrt();
597            let denom = std_error * factor;
598            if denom > MIN_LEVERAGE_DENOM {
599                r / denom
600            } else {
601                0.0
602            }
603        })
604        .collect();
605
606    // F-statistic
607    let f_statistic = (ss_regression / k as f64) / mse;
608    let f_p_value = f_p_value(f_statistic, k as f64, df as f64);
609
610    // RMSE and MAE
611    let rmse = std_error;
612    let mae: f64 = residuals_vec.iter().map(|&r| r.abs()).sum::<f64>() / n as f64;
613
614    // VIF
615    let vif = calculate_vif(x_vars, &names, n);
616
617    Ok(RegressionOutput {
618        coefficients: beta,
619        std_errors,
620        t_stats,
621        p_values,
622        conf_int_lower,
623        conf_int_upper,
624        r_squared,
625        adj_r_squared,
626        f_statistic,
627        f_p_value,
628        mse,
629        rmse,
630        mae,
631        std_error,
632        residuals: residuals_vec,
633        standardized_residuals,
634        predictions,
635        leverage,
636        vif,
637        n,
638        k,
639        df,
640        variable_names: names,
641    })
642}