Skip to main content

lib_jsl_optimization/
isotonic.rs

1//! Isotonic regression by the pool-adjacent-violators algorithm (SciPy's
2//! `optimize.isotonic_regression`).
3//!
4//! See the book entry [Brute force, isotonic regression and gradient checks](https://jwkunz.github.io/lib_jsl/book/optimization/brute-isotonic.html).
5
6use lib_jsl_core::ErrorsJSL;
7
8/// The result of [`isotonic_regression`].
9#[derive(Clone, Debug)]
10#[non_exhaustive]
11pub struct IsotonicResult {
12    /// The fitted monotone values, one per observation.
13    pub x: Vec<f64>,
14    /// The total weight of each block of equal fitted values.
15    pub weights: Vec<f64>,
16    /// The start of each block, followed by the number of observations: block `k` covers
17    /// `blocks[k]..blocks[k + 1]`.
18    pub blocks: Vec<usize>,
19}
20
21// ANCHOR: isotonic
22/// The weighted least-squares fit of `y` by a non-decreasing (or, with `increasing = false`,
23/// non-increasing) sequence, `min Σ wᵢ (xᵢ − yᵢ)²` subject to `x₁ ≤ x₂ ≤ … ≤ xₙ` (SciPy's
24/// `isotonic_regression`). The pool-adjacent-violators algorithm merges each new observation
25/// with the blocks before it while their weighted means are out of order; every block's value
26/// is its weighted mean, in O(n) time. `weights` default to one and must be positive.
27pub fn isotonic_regression(y: &[f64], weights: Option<&[f64]>, increasing: bool) -> Result<IsotonicResult, ErrorsJSL> {
28    let n = y.len();
29    let w: Vec<f64> = match weights {
30        Some(w) if w.len() != n => return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), n))),
31        Some(w) if w.iter().any(|v| v.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || !v.is_finite()) => {
32            return Err(ErrorsJSL::InvalidInputRange("isotonic_regression: weights must be positive and finite"));
33        }
34        Some(w) => w.to_vec(),
35        None => vec![1.0; n],
36    };
37    let sign = if increasing { 1.0 } else { -1.0 };
38    // Blocks as (weighted mean, weight, start).
39    let mut blocks: Vec<(f64, f64, usize)> = Vec::with_capacity(n);
40    for i in 0..n {
41        let (mut mean, mut weight, mut start) = (sign * y[i], w[i], i);
42        while let Some(&(m, wt, s)) = blocks.last() {
43            if m < mean {
44                break;
45            }
46            mean = (m * wt + mean * weight) / (wt + weight);
47            weight += wt;
48            start = s;
49            blocks.pop();
50        }
51        blocks.push((mean, weight, start));
52    }
53    let mut x = vec![0.0; n];
54    let mut starts: Vec<usize> = blocks.iter().map(|b| b.2).collect();
55    starts.push(n);
56    for (k, b) in blocks.iter().enumerate() {
57        x[starts[k]..starts[k + 1]].fill(sign * b.0);
58    }
59    Ok(IsotonicResult { x, weights: blocks.iter().map(|b| b.1).collect(), blocks: starts })
60}
61// ANCHOR_END: isotonic
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn pava_matches_definition() {
69        let y = [1.0, 3.0, 2.0, 4.0, 3.5, 5.0];
70        let r = isotonic_regression(&y, None, true).unwrap();
71        assert_eq!(r.x, vec![1.0, 2.5, 2.5, 3.75, 3.75, 5.0]);
72        assert_eq!(r.blocks, vec![0, 1, 3, 5, 6]);
73        assert_eq!(r.weights, vec![1.0, 2.0, 2.0, 1.0]);
74        // Decreasing, weighted: 5 and 6 pool to (5·1 + 6·3)/4.
75        let r = isotonic_regression(&[5.0, 6.0, 1.0], Some(&[1.0, 3.0, 1.0]), false).unwrap();
76        assert_eq!(r.x, vec![5.75, 5.75, 1.0]);
77        // Already monotone: unchanged, one block per observation.
78        let r = isotonic_regression(&[1.0, 2.0, 3.0], None, true).unwrap();
79        assert_eq!(r.blocks, vec![0, 1, 2, 3]);
80        assert!(isotonic_regression(&[1.0], Some(&[0.0]), true).is_err());
81    }
82}