Skip to main content

qualia_core_db/solvers/statistics/
mod.rs

1//! Statistics solver — the single, canonical home for numeric statistics.
2//!
3//! Zero-allocation kernels over caller-owned slices, a sibling to
4//! `solvers::linear_algebra`. This is where descriptive statistics, hypothesis
5//! tests, correlation, and binning live for the *whole* engine.
6//!
7//! **Composition rule (Modality-First):** specialized/domain libraries
8//! (`specialized_libs::statistical_computing`, `machine_learning`, …) marshal
9//! their domain data into a slice and call these functions. They MUST NOT carry
10//! their own `mean`/`variance`/`correlation` re-implementations. See
11//! `MODALITY_FIRST_CONSOLIDATION.md`.
12//!
13//! Probabilistic *logic* (Bayesian networks, truth-degree reasoning over quins)
14//! is a separate concern and lives in `modalities::probabilistic`; it may call
15//! into here for numeric work, but the two are not merged.
16
17pub mod anomaly;
18pub mod cohort_estimator;
19pub mod correlation;
20pub mod descriptive;
21pub mod distributions;
22pub mod histogram;
23pub mod hypothesis;
24pub mod information;
25pub mod regression;
26pub mod robust;
27pub mod timeseries;
28
29pub use correlation::{correlation_p_value, kendall, pearson, rank_into, spearman};
30pub use descriptive::{
31    covariance, kurtosis, max, mean, median_in_place, median_sorted, min, mode_in_place,
32    quantile_in_place, quantile_sorted, skewness, std_dev, sum, variance,
33};
34pub use histogram::{histogram_into, HistRange};
35pub use timeseries::{autocorrelation, exponential_smoothing_into, moving_average_into};
36
37pub use hypothesis::{
38    chi_square_gof, chi_square_independence, friedman, ks_1sample, mann_whitney_u, mcnemar,
39    one_sample_t, one_way_anova, paired_t, two_sample_t, AnovaResult, ChiSquareResult,
40    FriedmanResult, KolmogorovSmirnovResult, MannWhitneyResult, NonparametricResult, TTest,
41    TwoSampleTTest,
42};
43pub use information::{cross_entropy, entropy, kl_divergence, mutual_information_discrete};
44pub use regression::{
45    multiple_ols, simple_linear_regression, verify_regression_model, LinearRegression, MultipleOls,
46    VerificationReport,
47};
48pub use robust::{iqr, median_abs_deviation, trimmed_mean, winsorized_mean};
49
50/// Basic bootstrap mean (cold bounded, for calibration/validation).
51/// Resamples with replacement using provided RNG state (SplitMix style).
52/// Writes means for `num_samples` into `out`.
53pub fn bootstrap_means(
54    data: &[f64],
55    num_samples: usize,
56    seed: u64,
57    out: &mut [f64],
58) -> Result<usize, ()> {
59    if data.is_empty() || num_samples == 0 || out.len() < num_samples {
60        return Err(());
61    }
62    let mut rng = seed;
63    for s in 0..num_samples {
64        let mut sum = 0.0;
65        for _ in 0..data.len() {
66            // simple xorshift for demo
67            rng ^= rng << 13;
68            rng ^= rng >> 7;
69            rng ^= rng << 17;
70            let idx = (rng as usize) % data.len();
71            sum += data[idx];
72        }
73        out[s] = sum / data.len() as f64;
74    }
75    Ok(num_samples)
76}
77
78/// Ljung-Box test statistic for autocorrelation up to lag h.
79/// acf[0..h] are sample autocorrelations (from lag 1).
80pub fn ljung_box(acf: &[f64], n: usize, h: usize) -> f64 {
81    if h == 0 || acf.len() < h {
82        return f64::NAN;
83    }
84    let mut q = 0.0;
85    for k in 1..=h {
86        if k - 1 < acf.len() {
87            q += acf[k - 1].powi(2) / (n - k) as f64;
88        }
89    }
90    q * n as f64
91}
92
93/// Simple ADF-like stationarity proxy (negative means more stationary tendency).
94pub fn adf_proxy(series: &[f64]) -> f64 {
95    if series.len() < 3 {
96        return f64::NAN;
97    }
98    let mut sum_diff = 0.0;
99    let mut sum_lag = 0.0;
100    for i in 1..series.len() {
101        let diff = series[i] - series[i - 1];
102        sum_diff += diff * series[i - 1];
103        sum_lag += series[i - 1] * series[i - 1];
104    }
105    if sum_lag.abs() < 1e-12 {
106        return 0.0;
107    }
108    sum_diff / sum_lag
109}
110
111// Additional distributions (5.1-A progress)
112pub use distributions::{
113    beta_pdf, binomial_cdf, binomial_pmf, empirical_cdf, exponential_cdf, exponential_pdf,
114    gamma_pdf, laplace_cdf, laplace_pdf, lognormal_cdf, lognormal_pdf, poisson_cdf, poisson_pmf,
115    uniform_cdf, uniform_pdf, weibull_pdf,
116};