rs-stats 2.0.3

Statistics library in rust
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# Panic-Free Refactoring Plan

## Executive Summary

This document outlines a comprehensive plan to eliminate all panics from the `rs-stats` library and replace them with proper error handling using Rust's `Result` type. The goal is to make the library production-ready and panic-free.

**Target Version**: 2.0.0 (breaking changes expected)

**Estimated Effort**: High (affects all modules)

**Priority**: High (critical for production use)

---

## Table of Contents

1. [Current State Analysis]#current-state-analysis
2. [Error Type Design]#error-type-design
3. [Refactoring Strategy]#refactoring-strategy
4. [File-by-File Breakdown]#file-by-file-breakdown
5. [Testing Strategy]#testing-strategy
6. [Migration Path]#migration-path
7. [Breaking Changes]#breaking-changes
8. [Implementation Phases]#implementation-phases

---

## Current State Analysis

### Panic Sources Identified

#### 1. Explicit `panic!` Calls (3 locations)
- `src/utils/combinatorics.rs`: `permutation()` and `combination()` - 2 panics
- `src/regression/decision_tree.rs`: Multiple panics for type conversions - ~5 panics

#### 2. `.unwrap()` Calls (95+ instances)
- Type conversions: `T::from(n).unwrap()` - ~30 instances
- Array indexing: Direct indexing without bounds checks - ~20 instances
- Option unwrapping: `node.value.as_ref().unwrap()` - ~15 instances
- Test code: `.unwrap()` in tests - ~30 instances (acceptable)

#### 3. `.expect()` Calls (4 instances)
- `src/hypothesis_tests/chi_square_test.rs`: Type conversions - 4 instances

#### 4. Unsafe Array Indexing
- Direct indexing: `features[idx][feature_idx]` - Multiple locations
- No bounds checking before access

### Current Error Handling Patterns

#### Good Patterns (Keep)
- `src/prob/*.rs`: Uses `Option<f64>` for error cases
- `src/hypothesis_tests/t_test.rs`: Uses `Result<TTestResult, &'static str>`
- `src/regression/linear_regression.rs`: Uses `Result<(), String>` for `fit()`

#### Patterns to Improve
- String-based errors (`Result<(), String>`) - should use structured error type
- `&'static str` errors - should use structured error type
- `Option<T>` for some cases - should use `Result<T, E>` for better error context

---

## Error Type Design

### Proposed Error Type

```rust
// src/error.rs
use thiserror::Error;

/// Main error type for the rs-stats library
#[derive(Error, Debug, Clone, PartialEq)]
pub enum StatsError {
    /// Invalid input parameters
    #[error("Invalid input: {message}")]
    InvalidInput {
        message: String,
    },
    
    /// Type conversion failure
    #[error("Conversion error: {message}")]
    ConversionError {
        message: String,
    },
    
    /// Empty data provided when data is required
    #[error("Empty data: {message}")]
    EmptyData {
        message: String,
    },
    
    /// Dimension mismatch between arrays/vectors
    #[error("Dimension mismatch: {message}")]
    DimensionMismatch {
        message: String,
    },
    
    /// Numerical computation error (overflow, underflow, NaN, etc.)
    #[error("Numerical error: {message}")]
    NumericalError {
        message: String,
    },
    
    /// Model not fitted/trained before use
    #[error("Model not fitted: {message}")]
    NotFitted {
        message: String,
    },
    
    /// Invalid parameter value
    #[error("Invalid parameter: {message}")]
    InvalidParameter {
        message: String,
    },
    
    /// Index out of bounds
    #[error("Index out of bounds: {message}")]
    IndexOutOfBounds {
        message: String,
    },
    
    /// Division by zero or similar mathematical error
    #[error("Mathematical error: {message}")]
    MathematicalError {
        message: String,
    },
}

/// Convenience type alias for Result with StatsError
pub type StatsResult<T> = Result<T, StatsError>;

/// Helper macros for creating errors
#[macro_export]
macro_rules! invalid_input {
    ($($arg:tt)*) => {
        $crate::error::StatsError::InvalidInput {
            message: format!($($arg)*)
        }
    };
}

#[macro_export]
macro_rules! conversion_error {
    ($($arg:tt)*) => {
        $crate::error::StatsError::ConversionError {
            message: format!($($arg)*)
        }
    };
}
```

### Error Type Benefits

1. **Structured**: Each error variant has context
2. **Clone-able**: Can be stored and passed around
3. **Display**: Automatic `Display` implementation via `thiserror`
4. **Extensible**: Easy to add new error variants
5. **Type-safe**: Compiler ensures all errors are handled

---

## Refactoring Strategy

### Principles

1. **No Breaking Changes in v1.x**: Keep existing APIs working (deprecate, don't remove)
2. **Gradual Migration**: Introduce new error-returning APIs alongside old ones
3. **Backward Compatibility**: Provide migration helpers where possible
4. **Comprehensive Testing**: Ensure no regressions
5. **Documentation**: Update all docs with error handling examples

### Approach

1. **Phase 1**: Add error type and infrastructure
2. **Phase 2**: Fix critical panics (public APIs)
3. **Phase 3**: Fix internal panics
4. **Phase 4**: Update all APIs to use `Result`
5. **Phase 5**: Remove deprecated APIs (v2.0.0)

---

## File-by-File Breakdown

### Priority 1: Critical Public APIs

#### `src/utils/combinatorics.rs`
**Current Issues:**
- `permutation()`: Panics if `k > n`
- `combination()`: Panics if `k > n`

**Refactoring:**
```rust
// Before
pub fn permutation(n: u64, k: u64) -> u64 {
    if k > n {
        panic!("k cannot be greater than n");
    }
    // ...
}

// After
pub fn permutation(n: u64, k: u64) -> StatsResult<u64> {
    if k > n {
        return Err(StatsError::InvalidInput {
            message: format!("k ({}) cannot be greater than n ({})", k, n),
        });
    }
    Ok(((n - k + 1)..=n).product::<u64>())
}
```

**Breaking Change**: Yes (return type changes)
**Migration**: Provide `permutation_unchecked()` that panics for backward compat (deprecated)

---

#### `src/regression/decision_tree.rs`
**Current Issues:**
- Multiple `panic!` calls for type conversions (~5)
- `.unwrap()` calls for node access (~10)
- Array indexing without bounds checks

**Refactoring:**
```rust
// Before
let t_threshold = NumCast::from(threshold).unwrap_or_else(|| {
    panic!("Failed to convert threshold to the feature type");
});

// After
let t_threshold = NumCast::from(threshold).ok_or_else(|| {
    StatsError::ConversionError {
        message: "Failed to convert threshold to the feature type".to_string(),
    }
})?;
```

**Key Methods to Fix:**
- `fit()`: Already returns `Result`, but internal panics need fixing
- `predict()`: Should return `Result<T, StatsError>`
- `build_tree()`: Internal, but should propagate errors
- `find_best_split()`: Internal, but should return `Result`

**Breaking Change**: Partial (some methods already return `Result`)

---

#### `src/regression/linear_regression.rs`
**Current Issues:**
- `T::from(n).unwrap()` - ~5 instances
- Type conversions in `fit()` method

**Refactoring:**
```rust
// Before
let x_mean = x_cast.iter().fold(T::zero(), |acc, &x| acc + x) / T::from(n).unwrap();

// After
let n_as_t = T::from(n).ok_or_else(|| {
    StatsError::ConversionError {
        message: format!("Failed to convert {} to type T", n),
    }
})?;
let x_mean = x_cast.iter().fold(T::zero(), |acc, &x| acc + x) / n_as_t;
```

**Breaking Change**: No (already returns `Result<(), String>`)

---

#### `src/regression/multiple_linear_regression.rs`
**Current Issues:**
- Similar to `linear_regression.rs`
- `T::from(n).unwrap()` - ~10 instances

**Refactoring**: Same pattern as `linear_regression.rs`

**Breaking Change**: No (already returns `Result`)

---

#### `src/hypothesis_tests/chi_square_test.rs`
**Current Issues:**
- `.expect()` calls for type conversions - 4 instances

**Refactoring:**
```rust
// Before
let obs = observed[i]
    .to_f64()
    .expect("Failed to convert observed value to f64");

// After
let obs = observed[i]
    .to_f64()
    .ok_or_else(|| StatsError::ConversionError {
        message: format!("Failed to convert observed value at index {} to f64", i),
    })?;
```

**Breaking Change**: Yes (return type changes from `Option` to `Result`)

---

### Priority 2: Internal Functions

#### `src/prob/*.rs` modules
**Current State:**
- Most use `Option<f64>` which is acceptable
- Some could benefit from `Result` for better error context

**Refactoring Strategy:**
- Keep `Option<f64>` for simple cases (empty data)
- Consider `Result<f64, StatsError>` for complex errors
- No breaking changes needed immediately

---

#### `src/hypothesis_tests/t_test.rs`
**Current State:**
- Already uses `Result<TTestResult, &'static str>`
- Should migrate to `Result<TTestResult, StatsError>`

**Refactoring:**
```rust
// Before
pub fn one_sample_t_test<T>(...) -> Result<TTestResult, &'static str>

// After
pub fn one_sample_t_test<T>(...) -> StatsResult<TTestResult>
```

**Breaking Change**: Yes (error type changes)

---

#### `src/hypothesis_tests/anova.rs`
**Current State:**
- Returns `Option<AnovaResult>`
- Should return `Result<AnovaResult, StatsError>`

**Refactoring:**
```rust
// Before
pub fn one_way_anova<T>(...) -> Option<AnovaResult>

// After
pub fn one_way_anova<T>(...) -> StatsResult<AnovaResult>
```

**Breaking Change**: Yes (return type changes)

---

### Priority 3: Helper Functions

#### Array Indexing
**Current Issues:**
- Direct indexing: `features[idx][feature_idx]`
- No bounds checking

**Refactoring Pattern:**
```rust
// Before
let value = features[idx][feature_idx];

// After
let row = features.get(idx).ok_or_else(|| {
    StatsError::IndexOutOfBounds {
        message: format!("Row index {} out of bounds (len: {})", idx, features.len()),
    }
})?;
let value = row.get(feature_idx).ok_or_else(|| {
    StatsError::IndexOutOfBounds {
        message: format!("Column index {} out of bounds (len: {})", feature_idx, row.len()),
    }
})?;
```

---

## Testing Strategy

### Unit Tests

1. **Error Cases**: Test all error conditions
   ```rust
   #[test]
   fn test_permutation_invalid_input() {
       assert!(matches!(
           permutation(5, 10),
           Err(StatsError::InvalidInput { .. })
       ));
   }
   ```

2. **Success Cases**: Ensure existing functionality still works
   ```rust
   #[test]
   fn test_permutation_valid() {
       assert_eq!(permutation(5, 3).unwrap(), 60);
   }
   ```

3. **Edge Cases**: Test boundary conditions
   ```rust
   #[test]
   fn test_permutation_edge_cases() {
       assert_eq!(permutation(5, 5).unwrap(), 120);
       assert_eq!(permutation(5, 0).unwrap(), 1);
   }
   ```

### Integration Tests

1. **End-to-End**: Test complete workflows with error handling
2. **Error Propagation**: Ensure errors propagate correctly through call chains

### Regression Tests

1. **No Panics**: Add tests that verify no panics occur
   ```rust
   #[test]
   fn test_no_panics_on_invalid_input() {
       // This should not panic
       let _ = permutation(5, 10);
   }
   ```

---

## Migration Path

### Phase 1: Infrastructure (v1.3.0)
- [ ] Add `thiserror` dependency
- [ ] Create `src/error.rs` with `StatsError`
- [ ] Add error type to public API
- [ ] Create helper macros
- [ ] Update documentation

### Phase 2: Critical Fixes (v1.4.0)
- [ ] Fix `combinatorics.rs` panics
- [ ] Fix `decision_tree.rs` critical panics
- [ ] Fix `chi_square_test.rs` panics
- [ ] Add comprehensive tests

### Phase 3: Internal Refactoring (v1.5.0)
- [ ] Fix all `.unwrap()` calls in public APIs
- [ ] Fix array indexing issues
- [ ] Update error types from `String` to `StatsError`
- [ ] Add bounds checking everywhere

### Phase 4: API Standardization (v2.0.0)
- [ ] Migrate all `Option<T>` to `Result<T, StatsError>` where appropriate
- [ ] Migrate all `Result<T, String>` to `StatsResult<T>`
- [ ] Remove deprecated APIs
- [ ] Update all documentation
- [ ] Create migration guide

### Backward Compatibility

For v1.x releases, provide deprecated wrapper functions:

```rust
#[deprecated(note = "Use permutation() which returns Result")]
pub fn permutation_unchecked(n: u64, k: u64) -> u64 {
    permutation(n, k).expect("Invalid parameters")
}
```

---

## Breaking Changes

### Summary

| Module | Breaking Changes | Version |
|--------|-----------------|---------|
| `utils::combinatorics` | Return type: `u64``StatsResult<u64>` | 2.0.0 |
| `hypothesis_tests::chi_square_test` | Return type: `Option<T>``StatsResult<T>` | 2.0.0 |
| `hypothesis_tests::anova` | Return type: `Option<T>``StatsResult<T>` | 2.0.0 |
| `hypothesis_tests::t_test` | Error type: `&str``StatsError` | 2.0.0 |
| `regression::decision_tree` | Some methods: `T``StatsResult<T>` | 2.0.0 |

### Migration Guide Template

```markdown
## Migrating from v1.x to v2.0.0

### Combinatorics Functions

**Before:**
```rust
let result = permutation(5, 3);
```

**After:**
```rust
let result = permutation(5, 3)?;  // or handle error
match permutation(5, 3) {
    Ok(value) => println!("{}", value),
    Err(e) => eprintln!("Error: {}", e),
}
```
```

---

## Implementation Phases

### Phase 1: Foundation (Week 1)
**Goal**: Set up error handling infrastructure

- [ ] Add `thiserror = "1.0"` to `Cargo.toml`
- [ ] Create `src/error.rs`
- [ ] Export error type from `src/lib.rs`
- [ ] Write comprehensive error type tests
- [ ] Update `CHANGELOG.md`

**Deliverables:**
- Error type ready for use
- Documentation updated
- Tests passing

---

### Phase 2: Critical Panics (Week 2)
**Goal**: Fix all explicit panics in public APIs

- [ ] Fix `combinatorics.rs` (2 panics)
- [ ] Fix `decision_tree.rs` public methods (5 panics)
- [ ] Fix `chi_square_test.rs` (4 panics)
- [ ] Add tests for all error cases
- [ ] Update examples in documentation

**Deliverables:**
- No panics in public APIs
- All error cases tested
- Examples updated

---

### Phase 3: Internal Refactoring (Week 3-4)
**Goal**: Fix all `.unwrap()` and unsafe indexing

- [ ] Fix type conversions in regression modules
- [ ] Add bounds checking for all array access
- [ ] Fix internal helper functions
- [ ] Update error messages to be more descriptive
- [ ] Add error context where helpful

**Deliverables:**
- No `.unwrap()` in production code
- All array access is bounds-checked
- Better error messages

---

### Phase 4: API Standardization (Week 5-6)
**Goal**: Standardize all APIs to use `StatsResult`

- [ ] Migrate `Option<T>` to `StatsResult<T>` where appropriate
- [ ] Migrate `Result<T, String>` to `StatsResult<T>`
- [ ] Migrate `Result<T, &str>` to `StatsResult<T>`
- [ ] Update all documentation
- [ ] Create migration guide

**Deliverables:**
- Consistent error handling across library
- Complete documentation
- Migration guide ready

---

### Phase 5: Cleanup (Week 7)
**Goal**: Final polish and release preparation

- [ ] Remove deprecated functions (v2.0.0)
- [ ] Final documentation review
- [ ] Performance testing (ensure no regressions)
- [ ] Update version to 2.0.0
- [ ] Release notes

**Deliverables:**
- v2.0.0 ready for release
- All tests passing
- Documentation complete

---

## Success Criteria

### Must Have
- [ ] Zero panics in public APIs
- [ ] All errors use `StatsError` type
- [ ] Comprehensive test coverage for error cases
- [ ] Documentation updated with error handling examples
- [ ] Migration guide available

### Nice to Have
- [ ] Error context helpers (e.g., `.context()` method)
- [ ] Error recovery suggestions in error messages
- [ ] Performance benchmarks show no regression
- [ ] Backward compatibility shims for v1.x

---

## Risk Assessment

### High Risk
- **Breaking Changes**: Users need to update code
  - **Mitigation**: Provide migration guide and deprecated wrappers
- **Performance**: Error handling adds overhead
  - **Mitigation**: Benchmark and optimize hot paths

### Medium Risk
- **Test Coverage**: Need comprehensive error case tests
  - **Mitigation**: Systematic test writing, use coverage tools
- **Documentation**: Large amount of documentation to update
  - **Mitigation**: Incremental updates, prioritize public APIs

### Low Risk
- **Internal Refactoring**: Less visible to users
  - **Mitigation**: Thorough testing, gradual rollout

---

## Dependencies

### New Dependencies
```toml
[dependencies]
thiserror = "1.0"  # For error type derivation
```

### No Breaking Dependency Changes
- All existing dependencies remain compatible

---

## Timeline

| Phase | Duration | Start | End |
|-------|----------|-------|-----|
| Phase 1: Foundation | 1 week | TBD | TBD |
| Phase 2: Critical Panics | 1 week | TBD | TBD |
| Phase 3: Internal Refactoring | 2 weeks | TBD | TBD |
| Phase 4: API Standardization | 2 weeks | TBD | TBD |
| Phase 5: Cleanup | 1 week | TBD | TBD |
| **Total** | **7 weeks** | | |

---

## Notes

- This is a major refactoring that will require careful planning
- Consider creating a feature branch for the entire refactoring
- Regular testing and validation at each phase
- Consider user feedback during beta releases
- Performance testing is critical to ensure no regressions

---

## References

- [Rust Error Handling Best Practices]https://doc.rust-lang.org/book/ch09-00-error-handling.html
- [thiserror Documentation]https://docs.rs/thiserror/
- [Result Type Documentation]https://doc.rust-lang.org/std/result/

---

**Document Version**: 1.0  
**Last Updated**: 2025-11-17  
**Status**: Draft - Ready for Review