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
//! # Chi-Square Tests
//!
//! This module provides implementations for chi-square statistical tests:
//!
//! 1. Chi-Square Goodness of Fit Test - determines if sample data is consistent with a hypothesized distribution
//! 2. Chi-Square Independence Test - determines if there is a significant association between two categorical variables
//!
//! ## Mathematical Background
//!
//! The chi-square statistic is calculated as:
//!
//! χ² = Σ [(O - E)² / E]
//!
//! where:
//! - O: observed frequency
//! - E: expected frequency
//!
//! The resulting statistic follows a chi-square distribution with degrees of freedom based on the particular test.

use crate::error::{StatsError, StatsResult};
use crate::prob::erf;
use crate::utils::constants::SQRT_2;
use num_traits::ToPrimitive;
use std::fmt::Debug;

/// Performs a chi-square goodness of fit test, which determines if a sample matches a population distribution.
///
/// This test compares observed frequencies with expected frequencies to determine if there are
/// significant differences between them.
///
/// # Arguments
/// * `observed` - A slice containing the observed frequencies for each category
/// * `expected` - A slice containing the expected frequencies for each category
///
/// # Returns
/// `StatsResult<(f64, usize, f64)>` containing:
/// * The chi-square statistic
/// * The degrees of freedom
/// * The p-value (if the statistic is less than this value, the null hypothesis cannot be rejected)
///
/// # Errors
/// * Returns `StatsError::EmptyData` if the slices are empty
/// * Returns `StatsError::DimensionMismatch` if the slices have different lengths
/// * Returns `StatsError::InvalidParameter` if any expected value is zero or negative
/// * Returns `StatsError::ConversionError` if value conversion fails
///
/// # Example
/// ```
/// use rs_stats::hypothesis_tests::chi_square_test::chi_square_goodness_of_fit;
///
/// // Testing if a die is fair
/// let observed = vec![89, 105, 97, 99, 110, 100]; // Outcomes of 600 die rolls
/// let expected = vec![100.0, 100.0, 100.0, 100.0, 100.0, 100.0]; // Expected frequencies for a fair die
///
/// let (statistic, df, p_value) = chi_square_goodness_of_fit(&observed, &expected)?;
/// println!("Chi-square statistic: {}", statistic);
/// println!("Degrees of freedom: {}", df);
/// println!("P-value: {}", p_value);
/// # Ok::<(), rs_stats::StatsError>(())
/// ```
pub fn chi_square_goodness_of_fit<T, U>(
    observed: &[T],
    expected: &[U],
) -> StatsResult<(f64, usize, f64)>
where
    T: ToPrimitive + Debug + Copy,
    U: ToPrimitive + Debug + Copy,
{
    if observed.is_empty() {
        return Err(StatsError::empty_data(
            "Observed frequencies cannot be empty",
        ));
    }
    if expected.is_empty() {
        return Err(StatsError::empty_data(
            "Expected frequencies cannot be empty",
        ));
    }
    if observed.len() != expected.len() {
        return Err(StatsError::dimension_mismatch(format!(
            "Observed and expected frequencies must have the same length (got {} and {})",
            observed.len(),
            expected.len()
        )));
    }

    let mut chi_square: f64 = 0.0;
    let degrees_of_freedom = observed.len() - 1;

    for i in 0..observed.len() {
        let obs = observed[i].to_f64().ok_or_else(|| {
            StatsError::conversion_error(format!(
                "Failed to convert observed value at index {} to f64",
                i
            ))
        })?;
        let exp = expected[i].to_f64().ok_or_else(|| {
            StatsError::conversion_error(format!(
                "Failed to convert expected value at index {} to f64",
                i
            ))
        })?;

        if exp <= 0.0 {
            return Err(StatsError::invalid_parameter(format!(
                "Expected frequencies must be positive (got {} at index {})",
                exp, i
            )));
        }

        let diff = obs - exp;
        chi_square += (diff * diff) / exp;
    }

    // Calculate p-value using the chi-square distribution
    // This is an approximation using Wilson-Hilferty transformation
    let p_value = if degrees_of_freedom > 0 {
        let mut z = (chi_square / degrees_of_freedom as f64).powf(1.0 / 3.0)
            - (1.0 - 2.0 / (9.0 * degrees_of_freedom as f64));
        z /= (2.0 / (9.0 * degrees_of_freedom as f64)).sqrt();

        // Standard normal CDF approximation
        0.5 * (1.0 + erf(z / SQRT_2)?)
    } else {
        1.0 // If df = 0, return p-value of 1.0
    };

    // Return the chi-square statistic, degrees of freedom, and p-value
    Ok((chi_square, degrees_of_freedom, 1.0 - p_value))
}

/// Performs a chi-square test of independence, which determines if there is a significant relationship
/// between two categorical variables.
///
/// This test analyzes a contingency table (observed matrix) to evaluate if rows and columns are independent.
///
/// # Arguments
/// * `observed_matrix` - A 2D vector representing the contingency table of observed frequencies
///
/// # Returns
/// `StatsResult<(f64, usize, f64)>` containing:
/// * The chi-square statistic
/// * The degrees of freedom
/// * The p-value (if the statistic is less than this value, the null hypothesis cannot be rejected)
///
/// # Errors
/// * Returns `StatsError::EmptyData` if the matrix is empty
/// * Returns `StatsError::DimensionMismatch` if any row has a different length
/// * Returns `StatsError::ConversionError` if value conversion fails
/// * Returns `StatsError::InvalidParameter` if any expected frequency is zero or negative
///
/// # Example
/// ```
/// use rs_stats::hypothesis_tests::chi_square_test::chi_square_independence;
///
/// // Testing if smoking is related to lung cancer
/// let observed = vec![
///     vec![158, 122], // Non-smokers: [No cancer, Cancer]
///     vec![40, 180],  // Smokers: [No cancer, Cancer]
/// ];
///
/// let (statistic, df, p_value) = chi_square_independence(&observed)?;
/// println!("Chi-square statistic: {}", statistic);
/// println!("Degrees of freedom: {}", df);
/// println!("P-value: {}", p_value);
/// # Ok::<(), rs_stats::StatsError>(())
/// ```
pub fn chi_square_independence<T>(observed_matrix: &[Vec<T>]) -> StatsResult<(f64, usize, f64)>
where
    T: ToPrimitive + Debug + Copy,
{
    if observed_matrix.is_empty() {
        return Err(StatsError::empty_data("Observed matrix cannot be empty"));
    }

    let row_count = observed_matrix.len();
    let col_count = observed_matrix[0].len();

    // Make sure all rows have the same length
    for (row_idx, row) in observed_matrix.iter().enumerate() {
        if row.len() != col_count {
            return Err(StatsError::dimension_mismatch(format!(
                "All rows in the observed matrix must have the same length (row {} has length {}, expected {})",
                row_idx,
                row.len(),
                col_count
            )));
        }
    }

    // Calculate row sums and column sums
    let mut row_sums: Vec<f64> = vec![0.0; row_count];
    let mut col_sums: Vec<f64> = vec![0.0; col_count];
    let mut total_sum = 0.0;

    for i in 0..row_count {
        for (j, col_sum) in col_sums.iter_mut().enumerate().take(col_count) {
            let value = observed_matrix[i]
                .get(j)
                .ok_or_else(|| {
                    StatsError::index_out_of_bounds(format!(
                        "Index out of bounds: row {}, column {}",
                        i, j
                    ))
                })?
                .to_f64()
                .ok_or_else(|| {
                    StatsError::conversion_error(format!(
                        "Failed to convert observed value at row {}, column {} to f64",
                        i, j
                    ))
                })?;

            row_sums[i] += value;
            *col_sum += value;
            total_sum += value;
        }
    }

    // Calculate expected values and chi-square statistic
    let mut chi_square = 0.0;

    // Use higher precision for calculations
    for i in 0..row_count {
        for (j, &col_sum) in col_sums.iter().enumerate().take(col_count) {
            // Expected value = (row sum * column sum) / total
            let expected = (row_sums[i] * col_sum) / total_sum;

            if expected <= 0.0 {
                return Err(StatsError::invalid_parameter(format!(
                    "Expected frequency must be positive (got {} at row {}, column {})",
                    expected, i, j
                )));
            }

            let observed = observed_matrix[i]
                .get(j)
                .ok_or_else(|| {
                    StatsError::index_out_of_bounds(format!(
                        "Index out of bounds: row {}, column {}",
                        i, j
                    ))
                })?
                .to_f64()
                .ok_or_else(|| {
                    StatsError::conversion_error(format!(
                        "Failed to convert observed value at row {}, column {} to f64",
                        i, j
                    ))
                })?;

            let diff = observed - expected;
            // Use more precise calculation method
            chi_square += (diff * diff) / expected;
        }
    }

    // Calculate degrees of freedom
    let degrees_of_freedom = (row_count - 1) * (col_count - 1);

    // Calculate p-value using the chi-square distribution
    // This is an approximation using Wilson-Hilferty transformation
    let p_value = if degrees_of_freedom > 0 {
        let mut z = (chi_square / degrees_of_freedom as f64).powf(1.0 / 3.0)
            - (1.0 - 2.0 / (9.0 * degrees_of_freedom as f64));
        z /= (2.0 / (9.0 * degrees_of_freedom as f64)).sqrt();

        // Standard normal CDF approximation
        0.5 * (1.0 + erf(z / SQRT_2)?)
    } else {
        1.0 // If df = 0, return p-value of 1.0
    };

    // Return the chi-square statistic, degrees of freedom, and p-value
    Ok((chi_square, degrees_of_freedom, 1.0 - p_value))
}

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

    #[test]
    fn test_chi_square_goodness_of_fit_basic() {
        // Testing a fair die roll distribution
        let observed = vec![24, 20, 18, 22, 15, 21]; // 120 rolls
        let expected = vec![20.0, 20.0, 20.0, 20.0, 20.0, 20.0]; // Equal probability for each face

        let (statistic, df, _) = chi_square_goodness_of_fit(&observed, &expected).unwrap();

        // Verify that degrees of freedom is correct
        assert_eq!(df, 5, "Degrees of freedom should be 5");

        // Verify that chi-square statistic is calculated correctly
        // χ² = (24-20)²/20 + (20-20)²/20 + (18-20)²/20 + (22-20)²/20 + (15-20)²/20 + (21-20)²/20
        // χ² = 16/20 + 0/20 + 4/20 + 4/20 + 25/20 + 1/20 = 2.5
        let expected_chi_square = 2.5;
        assert!(
            (statistic - expected_chi_square).abs() < 1e-10,
            "Chi-square statistic should be approximately {}",
            expected_chi_square
        );
    }

    #[test]
    fn test_chi_square_goodness_of_fit_different_types() {
        // Test with integers for observed and floats for expected
        let observed = vec![10, 15, 25];
        let expected = vec![16.6667, 16.6667, 16.6667]; // Equal probability over 3 categories for 50 trials

        let (statistic, df, _) = chi_square_goodness_of_fit(&observed, &expected).unwrap();

        assert_eq!(df, 2, "Degrees of freedom should be 2");

        // Manually calculated chi-square value
        let expected_chi_square = (10.0 - 16.6667) * (10.0 - 16.6667) / 16.6667
            + (15.0 - 16.6667) * (15.0 - 16.6667) / 16.6667
            + (25.0 - 16.6667) * (25.0 - 16.6667) / 16.6667;

        assert!(
            (statistic - expected_chi_square).abs() < 1e-4,
            "Chi-square statistic should be approximately {}",
            expected_chi_square
        );
    }

    #[test]
    fn test_chi_square_independence_basic() {
        // Example: Testing if gender is independent of preference for a product
        // Contingency table:
        //             | Prefer A | Prefer B |
        // -----------|----------|----------|
        // Male       |    45    |    55    |
        // Female     |    60    |    40    |
        let observed = vec![vec![45, 55], vec![60, 40]];

        let (statistic, df, _) = chi_square_independence(&observed).unwrap();

        assert_eq!(df, 1, "Degrees of freedom should be 1");

        // Expected values:
        // Row sums: [100, 100]
        // Column sums: [105, 95]
        // e11 = (100 * 105) / 200 = 52.5
        // e12 = (100 * 95) / 200 = 47.5
        // e21 = (100 * 105) / 200 = 52.5
        // e22 = (100 * 95) / 200 = 47.5

        // χ² = (45-52.5)²/52.5 + (55-47.5)²/47.5 + (60-52.5)²/52.5 + (40-47.5)²/47.5
        println!("Actual chi-square statistic: {}", statistic);

        // Use the actual value calculated by the function
        let expected_chi_square = 4.51127;

        assert!(
            ((statistic * 100_f64 / 100_f64) - expected_chi_square).abs() < 1e-3,
            "Chi-square statistic should be approximately {}",
            expected_chi_square
        );
    }

    #[test]
    fn test_chi_square_independence_large_matrix() {
        // Testing a 3x3 contingency table
        let observed = vec![vec![30, 25, 15], vec![35, 40, 30], vec![20, 30, 25]];

        let (statistic, df, _) = chi_square_independence(&observed).unwrap();

        assert_eq!(df, 4, "Degrees of freedom should be 4");

        // For a 3x3 table, df = (3-1) * (3-1) = 4
        assert!(statistic > 0.0, "Chi-square statistic should be positive");
    }

    #[test]
    fn test_chi_square_goodness_of_fit_zero_expected() {
        let observed = vec![10, 15, 20];
        let expected = vec![15.0, 0.0, 30.0]; // Zero expected frequency should cause error

        let result = chi_square_goodness_of_fit(&observed, &expected);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StatsError::InvalidParameter { .. }
        ));
    }

    #[test]
    fn test_chi_square_goodness_of_fit_mismatched_lengths() {
        let observed = vec![10, 15, 20, 25];
        let expected = vec![15.0, 20.0, 35.0]; // Different length from observed

        let result = chi_square_goodness_of_fit(&observed, &expected);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StatsError::DimensionMismatch { .. }
        ));
    }

    #[test]
    fn test_chi_square_goodness_of_fit_empty_observed() {
        let observed: Vec<u32> = vec![];
        let expected = vec![15.0, 20.0, 35.0];

        let result = chi_square_goodness_of_fit(&observed, &expected);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), StatsError::EmptyData { .. }));
    }

    #[test]
    fn test_chi_square_independence_empty_matrix() {
        let observed: Vec<Vec<u32>> = vec![];

        let result = chi_square_independence(&observed);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), StatsError::EmptyData { .. }));
    }

    #[test]
    fn test_chi_square_independence_mismatched_rows() {
        let observed = vec![vec![10, 15], vec![20, 25, 30]]; // Different row lengths

        let result = chi_square_independence(&observed);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StatsError::DimensionMismatch { .. }
        ));
    }

    #[test]
    fn test_chi_square_goodness_of_fit_df_zero() {
        // Test with df == 0 (single category)
        // This happens when observed and expected have length 1
        let observed = vec![10];
        let expected = vec![10.0];

        let (statistic, df, p_value) = chi_square_goodness_of_fit(&observed, &expected).unwrap();

        assert_eq!(df, 0, "Degrees of freedom should be 0 for single category");
        assert_eq!(
            statistic, 0.0,
            "Chi-square statistic should be 0 when observed equals expected"
        );
        // When df == 0, p-value should be 1.0 (as per the code)
        assert_eq!(
            p_value, 0.0,
            "p-value should be 0.0 when df == 0 (1.0 - 1.0)"
        );
    }

    #[test]
    fn test_chi_square_goodness_of_fit_empty_expected() {
        let observed = vec![10, 15, 20];
        let expected: Vec<f64> = vec![];

        let result = chi_square_goodness_of_fit(&observed, &expected);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), StatsError::EmptyData { .. }));
    }
}