Skip to main content

wickra_core/indicators/
kendall_tau.rs

1//! Kendall's tau-b — rank correlation by concordant vs. discordant pairs.
2
3use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::traits::Indicator;
7
8/// `+1` / `0` / `-1` sign of `a − b`.
9fn sign(a: f64, b: f64) -> i32 {
10    if a > b {
11        1
12    } else if a < b {
13        -1
14    } else {
15        0
16    }
17}
18
19/// Kendall's tau-b — a rank correlation between two synchronised series based on
20/// the balance of **concordant** and **discordant** pairs, with a tie correction.
21///
22/// ```text
23/// over all pairs (i < j) in the window:
24///   concordant if (x_j − x_i) and (y_j − y_i) share a sign
25///   discordant if they have opposite signs
26///   tie_x / tie_y if the respective difference is zero
27/// n0  = N(N−1)/2
28/// tau_b = (n_concordant − n_discordant) / sqrt((n0 − tie_x)(n0 − tie_y))
29/// ```
30///
31/// Where [`PearsonCorrelation`](crate::PearsonCorrelation) measures *linear*
32/// co-movement and [`SpearmanCorrelation`](crate::SpearmanCorrelation) correlates
33/// ranks via their differences, Kendall's tau counts how often the two series move
34/// the **same direction** between every pair of observations. It is the most
35/// robust of the three to outliers and to non-linear-but-monotonic
36/// relationships, and the tau-b form corrects for ties so repeated values do not
37/// bias it. The output is in `[−1, +1]`: `+1` perfectly concordant, `−1`
38/// perfectly discordant, `0` no monotonic association.
39///
40/// The window holds the last `period` pairs and is recomputed each bar in
41/// O(`period²`). A window with no untied pairs on one side returns `0`. The first
42/// value lands after `period` inputs.
43///
44/// # Example
45///
46/// ```
47/// use wickra_core::{Indicator, KendallTau};
48///
49/// let mut indicator = KendallTau::new(20).unwrap();
50/// let mut last = None;
51/// for i in 0..40 {
52///     let x = f64::from(i);
53///     last = indicator.update((x, 2.0 * x)); // perfectly concordant
54/// }
55/// assert!((last.unwrap() - 1.0).abs() < 1e-9);
56/// ```
57#[derive(Debug, Clone)]
58pub struct KendallTau {
59    period: usize,
60    window: VecDeque<(f64, f64)>,
61    /// Pair counts over the live window, kept as pairs enter and leave: each
62    /// entering or leaving pair meets every other once, so a step costs
63    /// `O(period)` instead of recounting all `period²/2` pairs. Whole numbers,
64    /// so the result is exactly the recount's.
65    counts: PairCounts,
66    last: Option<f64>,
67}
68
69/// Concordant, discordant and tied pairs among a window's pairs.
70#[derive(Debug, Clone, Copy, Default)]
71struct PairCounts {
72    concordant: i64,
73    discordant: i64,
74    tie_x: i64,
75    tie_y: i64,
76}
77
78impl PairCounts {
79    /// Add (`step = 1`) or remove (`step = -1`) the pair `(a, b)`.
80    fn apply(&mut self, a: (f64, f64), b: (f64, f64), step: i64) {
81        let sx = sign(b.0, a.0);
82        let sy = sign(b.1, a.1);
83        if sx == 0 {
84            self.tie_x += step;
85        }
86        if sy == 0 {
87            self.tie_y += step;
88        }
89        let prod = sx * sy;
90        if prod > 0 {
91            self.concordant += step;
92        } else if prod < 0 {
93            self.discordant += step;
94        }
95    }
96}
97
98impl KendallTau {
99    /// Construct a rolling Kendall's tau-b over `period` pairs.
100    ///
101    /// # Errors
102    ///
103    /// Returns [`Error::InvalidPeriod`] if `period < 2` (a correlation needs at
104    /// least two pairs).
105    pub fn new(period: usize) -> Result<Self> {
106        if period < 2 {
107            return Err(Error::InvalidPeriod {
108                message: "Kendall tau needs period >= 2",
109            });
110        }
111        if period > crate::error::MAX_PERIOD {
112            return Err(Error::InvalidPeriod {
113                message: crate::error::PERIOD_ABOVE_MAX,
114            });
115        }
116        Ok(Self {
117            period,
118            window: VecDeque::with_capacity(period),
119            counts: PairCounts::default(),
120            last: None,
121        })
122    }
123
124    /// Configured window of pairs.
125    pub const fn period(&self) -> usize {
126        self.period
127    }
128
129    /// Current value if available.
130    pub const fn value(&self) -> Option<f64> {
131        self.last
132    }
133
134    fn compute(&self) -> f64 {
135        let len = self.window.len();
136        let PairCounts {
137            concordant,
138            discordant,
139            tie_x,
140            tie_y,
141        } = self.counts;
142        let n0 = (len * (len - 1) / 2) as f64;
143        let denom = ((n0 - tie_x as f64) * (n0 - tie_y as f64)).sqrt();
144        if denom == 0.0 {
145            return 0.0;
146        }
147        ((concordant - discordant) as f64 / denom).clamp(-1.0, 1.0)
148    }
149}
150
151impl Indicator for KendallTau {
152    type Input = (f64, f64);
153    type Output = f64;
154
155    #[inline]
156    fn update(&mut self, input: (f64, f64)) -> Option<f64> {
157        if !input.0.is_finite() || !input.1.is_finite() {
158            return None;
159        }
160        if self.window.len() == self.period {
161            let oldest = self.window.pop_front().expect("window is full");
162            for &other in &self.window {
163                self.counts.apply(oldest, other, -1);
164            }
165        }
166        for &other in &self.window {
167            self.counts.apply(other, input, 1);
168        }
169        self.window.push_back(input);
170        if self.window.len() < self.period {
171            return None;
172        }
173        let out = self.compute();
174        self.last = Some(out);
175        Some(out)
176    }
177
178    fn reset(&mut self) {
179        self.window.clear();
180        self.counts = PairCounts::default();
181        self.last = None;
182    }
183
184    #[inline]
185    fn warmup_period(&self) -> usize {
186        self.period
187    }
188
189    #[inline]
190    fn is_ready(&self) -> bool {
191        self.last.is_some()
192    }
193
194    #[inline]
195    fn name(&self) -> &'static str {
196        "KendallTau"
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::traits::BatchExt;
204    use approx::assert_relative_eq;
205
206    #[test]
207    fn rejects_period_below_two() {
208        assert!(matches!(
209            KendallTau::new(1),
210            Err(Error::InvalidPeriod { .. })
211        ));
212        assert!(KendallTau::new(2).is_ok());
213    }
214
215    #[test]
216    fn accessors_and_metadata() {
217        let k = KendallTau::new(20).unwrap();
218        assert_eq!(k.period(), 20);
219        assert_eq!(k.warmup_period(), 20);
220        assert_eq!(k.name(), "KendallTau");
221        assert!(!k.is_ready());
222        assert_eq!(k.value(), None);
223    }
224
225    #[test]
226    fn first_emission_at_warmup_period() {
227        let mut k = KendallTau::new(4).unwrap();
228        let out = k.batch(&[(1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0), (5.0, 5.0)]);
229        for v in out.iter().take(3) {
230            assert!(v.is_none());
231        }
232        assert!(out[3].is_some());
233    }
234
235    #[test]
236    fn monotone_increasing_is_one() {
237        let pairs: Vec<(f64, f64)> = (0..20)
238            .map(|i| (f64::from(i), 2.0 * f64::from(i) + 1.0))
239            .collect();
240        let last = KendallTau::new(10)
241            .unwrap()
242            .batch(&pairs)
243            .into_iter()
244            .flatten()
245            .last()
246            .unwrap();
247        assert_relative_eq!(last, 1.0, epsilon = 1e-9);
248    }
249
250    #[test]
251    fn monotone_decreasing_is_minus_one() {
252        let pairs: Vec<(f64, f64)> = (0..20)
253            .map(|i| (f64::from(i), -3.0 * f64::from(i)))
254            .collect();
255        let last = KendallTau::new(10)
256            .unwrap()
257            .batch(&pairs)
258            .into_iter()
259            .flatten()
260            .last()
261            .unwrap();
262        assert_relative_eq!(last, -1.0, epsilon = 1e-9);
263    }
264
265    #[test]
266    fn constant_channel_yields_zero() {
267        // y constant -> every y-difference is a tie -> denom 0 -> 0.
268        let pairs: Vec<(f64, f64)> = (0..20).map(|i| (f64::from(i), 7.0)).collect();
269        let last = KendallTau::new(8)
270            .unwrap()
271            .batch(&pairs)
272            .into_iter()
273            .flatten()
274            .last()
275            .unwrap();
276        assert_relative_eq!(last, 0.0, epsilon = 1e-12);
277    }
278
279    #[test]
280    fn output_in_range() {
281        let pairs: Vec<(f64, f64)> = (0..80)
282            .map(|i| {
283                let t = f64::from(i);
284                (100.0 + t.sin() * 5.0, 50.0 + (t * 0.3).cos() * 3.0)
285            })
286            .collect();
287        for v in KendallTau::new(20)
288            .unwrap()
289            .batch(&pairs)
290            .into_iter()
291            .flatten()
292        {
293            assert!((-1.0..=1.0).contains(&v));
294        }
295    }
296
297    #[test]
298    fn reset_clears_state() {
299        let mut k = KendallTau::new(4).unwrap();
300        k.batch(&[(1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0)]);
301        assert!(k.is_ready());
302        k.reset();
303        assert!(!k.is_ready());
304        assert_eq!(k.value(), None);
305        assert_eq!(k.update((1.0, 1.0)), None);
306    }
307
308    #[test]
309    fn batch_equals_streaming() {
310        let pairs: Vec<(f64, f64)> = (0..60)
311            .map(|i| {
312                let t = f64::from(i);
313                (t.sin(), (t * 0.5).cos())
314            })
315            .collect();
316        let batch = KendallTau::new(14).unwrap().batch(&pairs);
317        let mut b = KendallTau::new(14).unwrap();
318        let streamed: Vec<_> = pairs.iter().map(|p| b.update(*p)).collect();
319        assert_eq!(batch, streamed);
320    }
321
322    #[test]
323    fn ties_are_corrected() {
324        // Tied x values (points 0 and 1) and tied y values (points 1 and 2)
325        // exercise the tie_x / tie_y correction counters.
326        let mut k = KendallTau::new(4).unwrap();
327        assert_eq!(k.update((1.0, 1.0)), None);
328        assert_eq!(k.update((1.0, 2.0)), None);
329        assert_eq!(k.update((2.0, 2.0)), None);
330        let v = k.update((3.0, 3.0)).unwrap();
331        assert!((-1.0..=1.0).contains(&v), "got {v}");
332    }
333
334    #[test]
335    fn non_finite_input_returns_none() {
336        let mut k = KendallTau::new(2).unwrap();
337        assert_eq!(k.update((f64::NAN, 1.0)), None);
338        assert_eq!(k.update((1.0, f64::INFINITY)), None);
339        // The rejected ticks leave no trace: a fresh window still warms up.
340        assert_eq!(k.update((1.0, 2.0)), None);
341        assert!(k.update((2.0, 5.0)).is_some());
342    }
343}