linreg-core 0.8.1

Lightweight regression library (OLS, Ridge, Lasso, Elastic Net, WLS, LOESS, Polynomial) with 14 diagnostic tests, cross validation, and prediction intervals. Pure Rust - no external math dependencies. WASM, Python, FFI, and Excel XLL bindings.
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
//! Error types for the linear regression library.
//!
//! This module provides a comprehensive error type for all failure modes in
//! linear regression operations, including matrix operations, statistical
//! computations, and data parsing.

use std::fmt;

/// Error types for linear regression operations
///
/// # Example
///
/// ```
/// # use linreg_core::Error;
/// let err = Error::InvalidInput("negative value".to_string());
/// assert!(err.to_string().contains("Invalid input"));
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
    /// Matrix is singular (perfect multicollinearity).
    ///
    /// This occurs when one or more predictor variables are linear combinations
    /// of others, making the matrix non-invertible. Remove redundant variables
    /// to resolve this error.
    SingularMatrix,

    /// Insufficient data points for the model.
    ///
    /// OLS regression requires more observations than predictor variables.
    InsufficientData {
        /// Minimum number of observations required
        required: usize,
        /// Actual number of observations available
        available: usize,
    },

    /// Invalid input parameter.
    ///
    /// Indicates that an input parameter has an invalid value (e.g., negative
    /// variance, empty data arrays, incompatible dimensions).
    InvalidInput(String),

    /// Dimension mismatch in matrix/vector operations.
    ///
    /// This occurs when the dimensions of matrices or vectors are incompatible
    /// for the requested operation.
    DimensionMismatch(String),

    /// Computation failed due to numerical issues.
    ///
    /// This occurs when a numerical computation fails due to issues like
    /// singularity, non-convergence, or overflow/underflow.
    ComputationFailed(String),

    /// Parse error for JSON/CSV data.
    ///
    /// Raised when input data cannot be parsed as JSON or CSV.
    ParseError(String),

    /// Domain check failed (for WASM with domain restriction enabled).
    ///
    /// By default, the WASM module allows all domains. This error is only returned
    /// when the `LINREG_DOMAIN_RESTRICT` environment variable is set at build time
    /// and the module is accessed from an unauthorized domain.
    ///
    /// To enable domain restriction:
    /// ```bash
    /// LINREG_DOMAIN_RESTRICT=example.com,yoursite.com wasm-pack build
    /// ```
    DomainCheck(String),

    /// File I/O error during model save/load operations.
    ///
    /// Raised when reading or writing model files fails due to permissions,
    /// missing files, or other I/O issues.
    IoError(String),

    /// Serialization error when converting model to JSON.
    ///
    /// Raised when a model cannot be serialized to JSON format.
    SerializationError(String),

    /// Deserialization error when parsing model from JSON.
    ///
    /// Raised when a JSON file cannot be parsed into a model structure.
    DeserializationError(String),

    /// Incompatible format version when loading a model.
    ///
    /// Raised when the format version of a saved model is not compatible
    /// with the current library version.
    IncompatibleFormatVersion {
        /// Version from the file
        file_version: String,
        /// Version supported by this library
        supported: String,
    },

    /// Model type mismatch when loading a model.
    ///
    /// Raised when attempting to load a model as the wrong type
    /// (e.g., loading an OLS model as Ridge).
    ModelTypeMismatch {
        /// Expected model type
        expected: String,
        /// Actual model type found in file
        found: String,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::SingularMatrix => {
                write!(
                    f,
                    "Matrix is singular (perfect multicollinearity). Remove redundant variables."
                )
            },
            Error::InsufficientData {
                required,
                available,
            } => {
                write!(
                    f,
                    "Insufficient data: need at least {} observations, have {}",
                    required, available
                )
            },
            Error::InvalidInput(msg) => {
                write!(f, "Invalid input: {}", msg)
            },
            Error::DimensionMismatch(msg) => {
                write!(f, "Dimension mismatch: {}", msg)
            },
            Error::ComputationFailed(msg) => {
                write!(f, "Computation failed: {}", msg)
            },
            Error::ParseError(msg) => {
                write!(f, "Parse error: {}", msg)
            },
            Error::DomainCheck(msg) => {
                write!(f, "Domain check failed: {}", msg)
            },
            Error::IoError(msg) => {
                write!(f, "I/O error: {}", msg)
            },
            Error::SerializationError(msg) => {
                write!(f, "Serialization error: {}", msg)
            },
            Error::DeserializationError(msg) => {
                write!(f, "Deserialization error: {}", msg)
            },
            Error::IncompatibleFormatVersion { file_version, supported } => {
                write!(
                    f,
                    "Incompatible format version: file has version {}, supported version is {}",
                    file_version, supported
                )
            },
            Error::ModelTypeMismatch { expected, found } => {
                write!(
                    f,
                    "Model type mismatch: expected {}, found {}",
                    expected, found
                )
            },
        }
    }
}

impl std::error::Error for Error {}

/// Result type for linear regression operations.
///
/// Alias for `std::result::Result<T, Error>`.
///
/// # Example
///
/// ```
/// # use linreg_core::{Error, Result};
/// # fn falls_back() -> Result<f64> {
/// #     Ok(42.0)
/// # }
/// let result: Result<f64> = falls_back();
/// assert_eq!(result.unwrap(), 42.0);
/// ```
pub type Result<T> = std::result::Result<T, Error>;

// ============================================================================
// Helper Functions for WASM Integration
// ============================================================================
//
// These functions convert errors to JSON format for use in WASM bindings,
// enabling proper error reporting to JavaScript code.

/// Converts an error message to a JSON error string.
///
/// Creates a JSON object with a single "error" field containing the message.
/// Used in WASM bindings to return error information to JavaScript.
///
/// # Examples
///
/// ```
/// # use linreg_core::error_json;
/// let json = error_json("Invalid input");
/// assert_eq!(json, r#"{"error":"Invalid input"}"#);
/// ```
pub fn error_json(msg: &str) -> String {
    serde_json::json!({ "error": msg }).to_string()
}

/// Converts an [`Error`] to a JSON error string.
///
/// Convenience function that converts any error variant to its display
/// representation and wraps it in a JSON object.
///
/// # Examples
///
/// ```
/// # use linreg_core::Error;
/// # use linreg_core::error_to_json;
/// let err = Error::SingularMatrix;
/// let json = error_to_json(&err);
/// assert!(json.contains("singular"));
/// ```
pub fn error_to_json(err: &Error) -> String {
    error_json(&err.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Test Error::SingularMatrix Display implementation
    #[test]
    fn test_singular_matrix_display() {
        let err = Error::SingularMatrix;
        let msg = err.to_string();
        assert!(msg.contains("singular"));
        assert!(msg.contains("multicollinearity"));
    }

    /// Test Error::InsufficientData Display implementation
    #[test]
    fn test_insufficient_data_display() {
        let err = Error::InsufficientData {
            required: 10,
            available: 5,
        };
        let msg = err.to_string();
        assert!(msg.contains("Insufficient data"));
        assert!(msg.contains("10"));
        assert!(msg.contains("5"));
    }

    /// Test Error::InvalidInput Display implementation
    #[test]
    fn test_invalid_input_display() {
        let err = Error::InvalidInput("negative value".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Invalid input"));
        assert!(msg.contains("negative value"));
    }

    /// Test Error::DimensionMismatch Display implementation
    ///
    /// Covers lines 95-96: DimensionMismatch Display impl
    #[test]
    fn test_dimension_mismatch_display() {
        let err = Error::DimensionMismatch("matrix 3x3 cannot multiply with 2x2".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Dimension mismatch"));
        assert!(msg.contains("matrix 3x3"));
    }

    /// Test Error::ComputationFailed Display implementation
    ///
    /// Covers lines 98-99: ComputationFailed Display impl
    #[test]
    fn test_computation_failed_display() {
        let err = Error::ComputationFailed("QR decomposition failed".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Computation failed"));
        assert!(msg.contains("QR decomposition"));
    }

    /// Test Error::ParseError Display implementation
    #[test]
    fn test_parse_error_display() {
        let err = Error::ParseError("invalid JSON syntax".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Parse error"));
        assert!(msg.contains("JSON"));
    }

    /// Test Error::DomainCheck Display implementation
    #[test]
    fn test_domain_check_display() {
        let err = Error::DomainCheck("unauthorized domain".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Domain check failed"));
        assert!(msg.contains("unauthorized"));
    }

    /// Test error_json function
    #[test]
    fn test_error_json() {
        let json = error_json("test error");
        assert_eq!(json, r#"{"error":"test error"}"#);
    }

    /// Test error_to_json function with SingularMatrix
    #[test]
    fn test_error_to_json_singular_matrix() {
        let err = Error::SingularMatrix;
        let json = error_to_json(&err);
        assert!(json.contains(r#""error":"#));
        assert!(json.contains("singular"));
    }

    /// Test error_to_json function with DimensionMismatch
    #[test]
    fn test_error_to_json_dimension_mismatch() {
        let err = Error::DimensionMismatch("incompatible dimensions".to_string());
        let json = error_to_json(&err);
        assert!(json.contains(r#""error":"#));
        assert!(json.contains("Dimension"));
    }

    /// Test error_to_json function with ComputationFailed
    #[test]
    fn test_error_to_json_computation_failed() {
        let err = Error::ComputationFailed("convergence failure".to_string());
        let json = error_to_json(&err);
        assert!(json.contains(r#""error":"#));
        assert!(json.contains("Computation"));
    }

    /// Test Error PartialEq implementation
    #[test]
    fn test_error_partial_eq() {
        let err1 = Error::SingularMatrix;
        let err2 = Error::SingularMatrix;
        let err3 = Error::InvalidInput("test".to_string());

        assert_eq!(err1, err2);
        assert_ne!(err1, err3);
    }

    /// Test Error Clone implementation
    #[test]
    fn test_error_clone() {
        let err1 = Error::InvalidInput("test".to_string());
        let err2 = err1.clone();
        assert_eq!(err1, err2);
    }

    /// Test Error Debug implementation
    #[test]
    fn test_error_debug() {
        let err = Error::ComputationFailed("test failure".to_string());
        let debug_str = format!("{:?}", err);
        assert!(debug_str.contains("ComputationFailed"));
    }

    /// Test Result type alias
    #[test]
    fn test_result_type_alias() {
        fn returns_ok() -> Result<f64> {
            Ok(42.0)
        }
        fn returns_err() -> Result<f64> {
            Err(Error::InvalidInput("test".to_string()))
        }

        assert_eq!(returns_ok().unwrap(), 42.0);
        assert!(returns_err().is_err());
    }

    /// Test Error::IoError Display implementation
    #[test]
    fn test_io_error_display() {
        let err = Error::IoError("Failed to open file".to_string());
        let msg = err.to_string();
        assert!(msg.contains("I/O error"));
        assert!(msg.contains("Failed to open file"));
    }

    /// Test Error::SerializationError Display implementation
    #[test]
    fn test_serialization_error_display() {
        let err = Error::SerializationError("Failed to serialize model".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Serialization error"));
        assert!(msg.contains("Failed to serialize"));
    }

    /// Test Error::DeserializationError Display implementation
    #[test]
    fn test_deserialization_error_display() {
        let err = Error::DeserializationError("Invalid JSON".to_string());
        let msg = err.to_string();
        assert!(msg.contains("Deserialization error"));
        assert!(msg.contains("Invalid JSON"));
    }

    /// Test Error::IncompatibleFormatVersion Display implementation
    #[test]
    fn test_incompatible_format_version_display() {
        let err = Error::IncompatibleFormatVersion {
            file_version: "2.0".to_string(),
            supported: "1.0".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Incompatible format version"));
        assert!(msg.contains("2.0"));
        assert!(msg.contains("1.0"));
    }

    /// Test Error::ModelTypeMismatch Display implementation
    #[test]
    fn test_model_type_mismatch_display() {
        let err = Error::ModelTypeMismatch {
            expected: "OLS".to_string(),
            found: "Ridge".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Model type mismatch"));
        assert!(msg.contains("OLS"));
        assert!(msg.contains("Ridge"));
    }

    /// Test serialization errors work with error_to_json
    #[test]
    fn test_error_to_json_serialization() {
        let err = Error::SerializationError("test".to_string());
        let json = error_to_json(&err);
        assert!(json.contains(r#""error":"#));
        assert!(json.contains("Serialization"));
    }

    /// Test deserialization errors work with error_to_json
    #[test]
    fn test_error_to_json_deserialization() {
        let err = Error::DeserializationError("test".to_string());
        let json = error_to_json(&err);
        assert!(json.contains(r#""error":"#));
        assert!(json.contains("Deserialization"));
    }
}