Skip to main content

fastcit_core/
strategy.rs

1//! The data-bound conditional-independence test contract.
2//!
3//! Every test implements [`CITest`], operating on a shared [`Dataset`] and
4//! referring to the variables under test (`x`, `y`) and the conditioning set
5//! (`z`) by column index. Configuration lives on the test struct; the data
6//! lives on the [`Dataset`]. The provided [`CITest::test`] validates the query
7//! via [`validate_query`] before delegating to the required
8//! [`CITest::test_impl`]. The default [`CITest::is_independent`] turns a
9//! numeric [`CIResult`] into a boolean using the test's [`IndependenceRule`].
10
11use crate::dataset::Dataset;
12use crate::error::CIError;
13
14/// The numeric outcome of a conditional-independence test.
15#[derive(Debug, Clone, PartialEq)]
16pub struct CIResult {
17    /// The test statistic (e.g. chi-squared statistic, Pearson r, Fisher-z),
18    /// when the test defines one.
19    pub statistic: Option<f64>,
20    /// The p-value. Interpretation depends on the test's [`IndependenceRule`].
21    pub p_value: f64,
22    /// Degrees of freedom, when applicable.
23    pub dof: Option<usize>,
24    /// An effect-size summary (e.g. Cramér's V, |r|, |rho|), when applicable.
25    pub effect_size: Option<f64>,
26}
27
28/// How a p-value is turned into an independence decision at level `alpha`.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum IndependenceRule {
31    /// Standard null-of-independence tests: independent when `p >= alpha`.
32    PValueGe,
33    /// Equivalence / TOST tests: independent when `p < alpha`.
34    PValueLt,
35}
36
37impl IndependenceRule {
38    /// Whether independence holds for the given `p` at significance `alpha`.
39    #[must_use]
40    pub fn holds(self, p: f64, alpha: f64) -> bool {
41        match self {
42            IndependenceRule::PValueGe => p >= alpha,
43            IndependenceRule::PValueLt => p < alpha,
44        }
45    }
46}
47
48/// Compatibility name for the column kind a test consumes.
49pub use crate::dataset::ColumnKind as DataType;
50
51/// Static description of a test: its name, supported data types, whether it is
52/// symmetric in `x`/`y`, and its independence rule.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct TestMeta {
55    /// Stable identifier (e.g. `"chi_squared"`).
56    pub name: &'static str,
57    /// Data types the test supports.
58    pub data_types: &'static [DataType],
59    /// Whether swapping `x` and `y` leaves the result unchanged.
60    pub symmetric: bool,
61    /// How the p-value maps to an independence decision.
62    pub rule: IndependenceRule,
63}
64
65/// Validate a `(x, y, z)` query against `data` before running a test.
66///
67/// Checks, in order: all column indices are in range
68/// ([`CIError::UnknownColumn`]); `x != y`; `x`/`y` do not appear in `z`; `z`
69/// has no duplicates (all [`CIError::InvalidQuery`]). Called by the provided
70/// [`CITest::test`] so every test is validated uniformly.
71///
72/// # Errors
73///
74/// Returns the first violated rule as described above.
75pub fn validate_query(data: &Dataset, x: usize, y: usize, z: &[usize]) -> Result<(), CIError> {
76    let n_cols = data.n_cols();
77    for idx in [x, y].into_iter().chain(z.iter().copied()) {
78        if idx >= n_cols {
79            return Err(CIError::UnknownColumn(format!("column index {idx}")));
80        }
81    }
82    if x == y {
83        return Err(CIError::InvalidQuery(format!(
84            "x and y must be different columns (both are column index {x})"
85        )));
86    }
87    for (label, idx) in [("x", x), ("y", y)] {
88        if z.contains(&idx) {
89            return Err(CIError::InvalidQuery(format!(
90                "{label} (column index {idx}) must not appear in the conditioning set z"
91            )));
92        }
93    }
94    for i in 0..z.len() {
95        if z[i + 1..].contains(&z[i]) {
96            return Err(CIError::InvalidQuery(format!(
97                "conditioning set z contains column index {} more than once",
98                z[i]
99            )));
100        }
101    }
102    Ok(())
103}
104
105/// A stateless conditional-independence test operating on a supplied [`Dataset`].
106pub trait CITest: Send + Sync {
107    /// Test-specific computation for `x ⊥ y | z`. Implementations may assume
108    /// the query has already been validated by [`CITest::test`]; call sites
109    /// should use [`CITest::test`], not this method.
110    ///
111    /// # Errors
112    ///
113    /// Returns a [`CIError`] if the data is unsuitable (wrong column kind,
114    /// degenerate input, dimension mismatch) or a numerical routine fails.
115    fn test_impl(
116        &self,
117        data: &Dataset,
118        x: usize,
119        y: usize,
120        z: &[usize],
121    ) -> Result<CIResult, CIError>;
122
123    /// Check the test's own configuration against `data` (e.g. kernel
124    /// parameters, column names). The default accepts everything. Bindings call
125    /// this at construction so a bad configuration fails early; the provided
126    /// [`CITest::test`] also runs it on every call.
127    ///
128    /// # Errors
129    ///
130    /// Returns a [`CIError`] (typically [`CIError::InvalidConfig`] or
131    /// [`CIError::UnknownColumn`]) describing the invalid setting.
132    fn validate(&self, _data: &Dataset) -> Result<(), CIError> {
133        Ok(())
134    }
135
136    /// Run the test for `x ⊥ y | z` after validating the query
137    /// (see [`validate_query`]) and the configuration ([`CITest::validate`]).
138    ///
139    /// Implementors should not override this method; implement
140    /// [`CITest::test_impl`] instead, so the uniform validation is preserved.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`CIError::UnknownColumn`] / [`CIError::InvalidQuery`] for a
145    /// malformed query, or any error from [`CITest::test_impl`].
146    fn test(&self, data: &Dataset, x: usize, y: usize, z: &[usize]) -> Result<CIResult, CIError> {
147        validate_query(data, x, y, z)?;
148        self.validate(data)?;
149        self.test_impl(data, x, y, z)
150    }
151
152    /// Static metadata describing this test.
153    fn meta(&self) -> TestMeta;
154
155    /// Convenience wrapper returning an independence decision at level `alpha`.
156    ///
157    /// # Errors
158    ///
159    /// Propagates any error from [`CITest::test`].
160    fn is_independent(
161        &self,
162        data: &Dataset,
163        x: usize,
164        y: usize,
165        z: &[usize],
166        alpha: f64,
167    ) -> Result<bool, CIError> {
168        if !alpha.is_finite() {
169            return Err(CIError::InvalidQuery(format!(
170                "significance level must be finite, got {alpha}"
171            )));
172        }
173        Ok(self
174            .meta()
175            .rule
176            .holds(self.test(data, x, y, z)?.p_value, alpha))
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn rule_ge() {
186        assert!(IndependenceRule::PValueGe.holds(0.5, 0.05));
187        assert!(IndependenceRule::PValueGe.holds(0.05, 0.05));
188        assert!(!IndependenceRule::PValueGe.holds(0.01, 0.05));
189    }
190
191    #[test]
192    fn rule_lt() {
193        assert!(IndependenceRule::PValueLt.holds(0.01, 0.05));
194        assert!(!IndependenceRule::PValueLt.holds(0.05, 0.05));
195        assert!(!IndependenceRule::PValueLt.holds(0.5, 0.05));
196    }
197
198    use crate::ci_tests::ChiSquared;
199    use crate::dataset::{ColumnKind, Dataset};
200
201    fn two_col_data() -> Dataset {
202        Dataset::from_columns(vec![
203            ("a".into(), ColumnKind::Discrete, vec![1., 2., 1., 2.]),
204            ("b".into(), ColumnKind::Discrete, vec![1., 1., 2., 2.]),
205            ("c".into(), ColumnKind::Discrete, vec![1., 2., 2., 1.]),
206        ])
207        .unwrap()
208    }
209
210    #[test]
211    fn rejects_x_equals_y() {
212        let data = two_col_data();
213        let err = ChiSquared::new().test(&data, 0, 0, &[]).unwrap_err();
214        assert!(
215            matches!(err, crate::error::CIError::InvalidQuery(_)),
216            "{err}"
217        );
218    }
219
220    #[test]
221    fn rejects_x_or_y_in_z() {
222        let data = two_col_data();
223        assert!(matches!(
224            ChiSquared::new().test(&data, 0, 1, &[0]),
225            Err(crate::error::CIError::InvalidQuery(_))
226        ));
227        assert!(matches!(
228            ChiSquared::new().test(&data, 0, 1, &[1]),
229            Err(crate::error::CIError::InvalidQuery(_))
230        ));
231    }
232
233    #[test]
234    fn rejects_duplicate_z() {
235        let data = two_col_data();
236        assert!(matches!(
237            ChiSquared::new().test(&data, 0, 1, &[2, 2]),
238            Err(crate::error::CIError::InvalidQuery(_))
239        ));
240    }
241
242    #[test]
243    fn rejects_out_of_range_indices() {
244        let data = two_col_data();
245        assert!(matches!(
246            ChiSquared::new().test(&data, 9, 1, &[]),
247            Err(crate::error::CIError::UnknownColumn(_))
248        ));
249        assert!(matches!(
250            ChiSquared::new().test(&data, 0, 1, &[9]),
251            Err(crate::error::CIError::UnknownColumn(_))
252        ));
253        // is_independent goes through the same validation.
254        assert!(matches!(
255            ChiSquared::new().is_independent(&data, 0, 0, &[], 0.05),
256            Err(crate::error::CIError::InvalidQuery(_))
257        ));
258    }
259
260    #[test]
261    fn rejects_non_finite_significance_levels() {
262        let data = two_col_data();
263        let test = ChiSquared::new();
264
265        for alpha in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
266            let err = test.is_independent(&data, 0, 1, &[], alpha).unwrap_err();
267            assert!(
268                matches!(
269                    err,
270                    crate::error::CIError::InvalidQuery(ref message)
271                        if message.contains("significance level must be finite")
272                ),
273                "alpha={alpha}: {err}"
274            );
275        }
276    }
277}