Skip to main content

Crate linreg_core

Crate linreg_core 

Source
Expand description

§linreg-core

A lightweight, self-contained linear regression library in pure Rust.

No external math dependencies. All linear algebra (matrices, QR decomposition) and statistical functions (distributions, hypothesis tests) are implemented from scratch. Compiles to WebAssembly for browser use or runs as a native Rust crate.

§What This Does

  • OLS Regression — Ordinary Least Squares with numerically stable QR decomposition
  • Regularized Regression — Ridge, Lasso, and Elastic Net via coordinate descent
  • Diagnostic Tests — 8+ statistical tests for validating regression assumptions
  • WASM Support — Same API works in browsers via WebAssembly

§Quick Start

§Native Rust

Add to Cargo.toml (no WASM overhead):

[dependencies]
linreg-core = { version = "0.6", default-features = false }
use linreg_core::core::ols_regression;

let y = vec![2.5, 3.7, 4.2, 5.1, 6.3];
let x1 = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let x2 = vec![2.0, 4.0, 5.0, 4.0, 3.0];
let names = vec!["Intercept".into(), "Temp".into(), "Pressure".into()];

let result = ols_regression(&y, &[x1, x2], &names)?;
println!("R²: {}", result.r_squared);
println!("F-statistic: {}", result.f_statistic);

§WebAssembly (JavaScript)

[dependencies]
linreg-core = "0.6"

Build with wasm-pack build --target web, then use in JavaScript:

import init, { ols_regression } from './linreg_core.js';
await init();

const result = JSON.parse(ols_regression(
    JSON.stringify([2.5, 3.7, 4.2, 5.1, 6.3]),
    JSON.stringify([[1,2,3,4,5], [2,4,5,4,3]]),
    JSON.stringify(["Intercept", "X1", "X2"])
));
console.log("R²:", result.r_squared);

§Regularized Regression

use linreg_core::regularized::{ridge, lasso};
use linreg_core::linalg::Matrix;

let x = Matrix::new(100, 3, vec![0.0; 300]);
let y = vec![0.0; 100];

// Ridge regression (L2 penalty - shrinks coefficients, handles multicollinearity)
let ridge_result = ridge::ridge_fit(&x, &y, &ridge::RidgeFitOptions {
    lambda: 1.0,
    intercept: true,
    standardize: true,
    ..Default::default()
})?;

// Lasso regression (L1 penalty - does variable selection by zeroing coefficients)
let lasso_result = lasso::lasso_fit(&x, &y, &lasso::LassoFitOptions {
    lambda: 0.1,
    intercept: true,
    standardize: true,
    ..Default::default()
})?;

§Diagnostic Tests

After fitting a model, validate its assumptions:

TestTests ForUse When
diagnostics::rainbow_testLinearityChecking if relationships are linear
diagnostics::harvey_collier_testFunctional formSuspecting model misspecification
diagnostics::breusch_pagan_testHeteroscedasticityVariance changes with predictors
diagnostics::white_testHeteroscedasticityMore general than Breusch-Pagan
diagnostics::shapiro_wilk_testNormalitySmall to moderate samples (n ≤ 5000)
diagnostics::jarque_bera_testNormalityLarge samples, skewness/kurtosis
diagnostics::anderson_darling_testNormalityTail-sensitive, any sample size
diagnostics::durbin_watson_testAutocorrelationTime series or ordered data
diagnostics::cooks_distance_testInfluential pointsIdentifying high-impact observations
use linreg_core::diagnostics::{rainbow_test, breusch_pagan_test, RainbowMethod};

// Rainbow test for linearity
let rainbow = rainbow_test(&y, &[x1.clone(), x2.clone()], 0.5, RainbowMethod::R)?;
if rainbow.r_result.as_ref().map_or(false, |r| r.p_value < 0.05) {
    println!("Warning: relationship may be non-linear");
}

// Breusch-Pagan test for heteroscedasticity
let bp = breusch_pagan_test(&y, &[x1, x2])?;
if bp.p_value < 0.05 {
    println!("Warning: residuals have non-constant variance");
}

§Feature Flags

FlagDefaultDescription
wasmYesEnables WASM bindings and browser support
validationNoIncludes test data for validation tests

For native-only builds (smaller binary, no WASM deps):

linreg-core = { version = "0.6", default-features = false }

§Why This Library?

  • Zero dependencies — No nalgebra, no statrs, no ndarray. Pure Rust.
  • Validated — Outputs match R’s lm() and Python’s statsmodels
  • WASM-ready — Same code runs natively and in browsers
  • Small — Core is ~2000 lines, compiles quickly
  • Permissive license — MIT OR Apache-2.0

§Module Structure

  • core — OLS regression, coefficients, residuals, VIF
  • regularized — Ridge, Lasso, Elastic Net, regularization paths
  • diagnostics — All diagnostic tests (linearity, heteroscedasticity, normality, autocorrelation)
  • distributions — Statistical distributions (t, F, χ², normal, beta, gamma)
  • linalg — Matrix operations, QR decomposition, linear system solver
  • error — Error types and Result alias

§Disclaimer

This library is under active development and has not reached 1.0 stability. While outputs are validated against R and Python implementations, do not use this library for critical applications (medical, financial, safety-critical systems) without independent verification. See the LICENSE for full terms. The software is provided “as is” without warranty of any kind.

Re-exports§

pub use core::aic;
pub use core::aic_python;
pub use core::bic;
pub use core::bic_python;
pub use core::log_likelihood;
pub use core::RegressionOutput;
pub use core::VifResult;
pub use diagnostics::BGTestType;
pub use diagnostics::BreuschGodfreyResult;
pub use diagnostics::CooksDistanceResult;
pub use diagnostics::DiagnosticTestResult;
pub use diagnostics::RainbowMethod;
pub use diagnostics::RainbowSingleResult;
pub use diagnostics::RainbowTestOutput;
pub use diagnostics::ResetType;
pub use diagnostics::WhiteMethod;
pub use diagnostics::WhiteSingleResult;
pub use diagnostics::WhiteTestOutput;
pub use loess::loess_fit;
pub use loess::LoessFit;
pub use loess::LoessOptions;
pub use weighted_regression::wls_regression;
pub use weighted_regression::WlsFit;
pub use diagnostics::rainbow_test as rainbow_test_core;
pub use diagnostics::white_test as white_test_core;
pub use error::error_json;
pub use error::error_to_json;
pub use error::Error;
pub use error::Result;

Modules§

core
Core OLS regression implementation.
diagnostics
Statistical diagnostic tests for linear regression assumptions.
distributions
Custom statistical special functions and distribution utilities (CDF/SF/quantiles), primarily to avoid pulling in statrs for regression diagnostics.
error
Error types for the linear regression library.
linalg
Minimal Linear Algebra module to replace nalgebra dependency.
loess
LOESS (Locally Estimated Scatterplot Smoothing)
regularized
Ridge and Lasso regression (glmnet-compatible implementations).
stats
Basic statistical utility functions.
wasm
WASM-specific bindings for linreg-core
weighted_regression
Weighted regression methods