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
use ndarray::{ArrayBase, Data, Ix1};
use std::fmt::Debug;

/// Helper methods for one dimensional numeric arrays
pub trait VectorExtensions<T> {
    /// get the monotonic property of the vector
    fn monotonic_prop(&self) -> Monotonic;

    /// Get the index of the next lower value inside the vector.
    /// This is not guaranteed to return the index of an exact match.
    ///
    /// This will never return the last index of the vector.
    /// when x is out of bounds it will either return `0` or `self.len() - 2`
    /// depending on which side it is out of bounds
    ///
    /// # Warning
    /// this method requires the [`monotonic_prop`](VectorExtensions::monotonic_prop) to be
    /// `Monotonic::Rising { strict: true }`
    /// otherwise the behaviour is undefined
    fn get_lower_index(&self, x: T) -> usize;
}

/// Describes the monotonic property of a vector
#[derive(Debug)]
pub enum Monotonic {
    Rising { strict: bool },
    Falling { strict: bool },
    NotMonotonic,
}
use num_traits::{cast, Num, NumCast};
use Monotonic::*;

use crate::interp1d::Linear;

impl<S> VectorExtensions<S::Elem> for ArrayBase<S, Ix1>
where
    S: Data,
    S::Elem: Debug + PartialOrd + Num + NumCast + Copy,
{
    fn monotonic_prop(&self) -> Monotonic {
        if self.len() <= 1 {
            return NotMonotonic;
        };

        self.windows(2)
            .into_iter()
            .try_fold(MonotonicState::start(), |state, items| {
                let a = items[0];
                let b = items[1];
                state.update(a, b).short_circuit()
            })
            .map_or_else(|mon| mon, |state| state.finish())
    }

    fn get_lower_index(&self, x: S::Elem) -> usize {
        // the vector should be strictly monotonic rising, otherwise we will
        // produce grabage

        // check in range, otherwise return the first or second last index
        // this allows for extrapolation
        if x <= self[0] {
            return 0;
        }
        if x >= self[self.len() - 1] {
            return self.len() - 2;
        }

        // We assume that the spacing is even. So we can calculate the index
        // and check it. This finishes in O(1) for even spaced axis.
        let mut range = (0usize, self.len() - 1);
        let p1 = (
            self[range.0],
            cast(range.0)
                .unwrap_or_else(|| unimplemented!("casting from usize should always work!")),
        );
        let p2 = (
            self[range.1],
            cast(range.1)
                .unwrap_or_else(|| unimplemented!("casting from usize should always work!")),
        );

        let mid = Linear::calc_frac(p1, p2, x);
        let mid_idx: usize =
            cast(mid).unwrap_or_else(|| unimplemented!("failed to convert {mid:?} to usize"));

        let mid_x = self[mid_idx];

        if mid_x <= x && x < self[mid_idx + 1] {
            return mid_idx;
        }
        if mid_x <= x {
            // why is this faster than `mid_x < x`???
            range.0 = mid_idx;
        } else {
            range.1 = mid_idx;
        }

        // the spacing was apparently not even, do binary search
        // O(log n)
        while range.0 + 1 < range.1 {
            let mid_idx = (range.1 - range.0) / 2 + range.0;
            let mid_x = self[mid_idx];

            if mid_x <= x {
                range.0 = mid_idx;
            } else {
                range.1 = mid_idx;
            }
        }
        range.0
    }
}

/// A State Machine for finding the monotonic property of an array
#[derive(Debug)]
enum MonotonicState {
    Init,
    NotStrict,
    Likely(Monotonic),
}

impl MonotonicState {
    /// start the state machine
    fn start() -> Self {
        Self::Init
    }

    /// update the state machine with two consecutive values from the vector
    fn update<T>(self, a: T, b: T) -> Self
    where
        T: PartialOrd,
    {
        use MonotonicState::*;
        match self {
            Init => {
                if a < b {
                    Likely(Rising { strict: true })
                } else if a == b {
                    NotStrict
                } else {
                    Likely(Falling { strict: true })
                }
            }
            NotStrict => {
                if a < b {
                    Likely(Rising { strict: false })
                } else if a == b {
                    NotStrict
                } else {
                    Likely(Falling { strict: false })
                }
            }
            Likely(Rising { strict }) => {
                if a == b {
                    Likely(Rising { strict: false })
                } else if a < b {
                    Likely(Rising { strict })
                } else {
                    Likely(NotMonotonic)
                }
            }
            Likely(Falling { strict }) => {
                if a == b {
                    Likely(Falling { strict: false })
                } else if a > b {
                    Likely(Falling { strict })
                } else {
                    Likely(NotMonotonic)
                }
            }
            Likely(NotMonotonic) => Likely(NotMonotonic),
        }
    }

    /// return `Err(Monotonic)` when the state machine can no longer change its state
    /// otherwise retruns `Ok(self)`
    ///
    /// This can be used with the [`Iterator::try_fold()`] method short-circuiting
    /// the iterator.
    fn short_circuit(self) -> Result<Self, Monotonic> {
        match self {
            MonotonicState::Likely(NotMonotonic) => Err(NotMonotonic),
            _ => Ok(self),
        }
    }

    /// get the final value of the state machine
    ///
    /// # panics
    /// when the state machine is still in the `Init` State
    fn finish(self) -> Monotonic {
        match self {
            MonotonicState::Init => panic!("`MonotonicState::update` was never called"),
            MonotonicState::NotStrict => NotMonotonic,
            MonotonicState::Likely(mon) => mon,
        }
    }
}

#[cfg(test)]
mod test {
    use ndarray::{array, s, Array, Array1};

    use super::{Monotonic, VectorExtensions};

    macro_rules! test_index {
        ($i:expr, $q:expr) => {
            let data = Array::linspace(0.0, 10.0, 11);
            assert_eq!($i, data.get_lower_index($q));
        };
        ($i:expr, $q:expr, exp) => {
            let data = Array::from_iter((0..11).map(|x| 2f64.powi(x)));
            assert_eq!($i, data.get_lower_index($q));
        };
        ($i:expr, $q:expr, ln) => {
            let data = Array::from_iter((0..11).map(|x| (x as f64).ln_1p()));
            assert_eq!($i, data.get_lower_index($q));
        };
    }

    #[test]
    fn test_outside_left() {
        test_index!(0, -1.0);
    }

    #[test]
    fn test_outside_right() {
        test_index!(9, 25.0);
    }

    #[test]
    fn test_left_border() {
        test_index!(0, 0.0);
    }

    #[test]
    fn test_right_border() {
        test_index!(9, 10.0);
    }

    #[test]
    fn test_exact_index() {
        for i in 0..10 {
            test_index!(i, i as f64);
        }
    }

    #[test]
    fn test_index() {
        for mut i in 0..100usize {
            let q = i as f64 / 10.0;
            i /= 10;
            test_index!(i, q);
        }
    }

    #[test]
    fn test_pos_inf_index() {
        test_index!(9, f64::INFINITY);
    }

    #[test]
    fn test_neg_inf_index() {
        test_index!(0, f64::NEG_INFINITY);
    }

    #[test]
    #[should_panic(expected = "not implemented: failed to convert NaN to usize")]
    fn test_nan() {
        test_index!(0, f64::NAN);
    }

    #[test]
    fn test_exponential_exact_index() {
        for (i, q) in (0..10).map(|x| (x as usize, 2f64.powi(x))) {
            test_index!(i, q, exp);
        }
    }

    #[test]
    fn test_exponential_index() {
        for (i, q) in (0..100usize).map(|x| (x / 10, 2f64.powf(x as f64 / 10.0))) {
            test_index!(i, q, exp);
        }
    }

    #[test]
    fn test_exponential_right_border() {
        test_index!(9, 1024.0, exp);
    }

    #[test]
    fn test_exponential_left_border() {
        test_index!(0, 1.0, exp);
    }

    #[test]
    fn test_log() {
        for (i, q) in (0..100usize).map(|x| (x / 10, (x as f64 / 10.0).ln_1p())) {
            test_index!(i, q, ln);
        }
    }

    macro_rules! test_monotonic {
        ($d:ident, $expected:pat) => {
            match $d.monotonic_prop() {
                $expected => (),
                value => panic!("{}", format!("got {value:?}")),
            };
            match $d.slice(s![..;1]).monotonic_prop() {
                $expected => (),
                _ => panic!(),
            };
        };
    }

    // test with f64
    #[test]
    fn test_strict_monotonic_rising_f64() {
        let data: Array1<f64> = array![1.1, 2.0, 3.123, 4.5];
        test_monotonic!(data, Monotonic::Rising { strict: true });
    }

    #[test]
    fn test_monotonic_rising_f64() {
        let data: Array1<f64> = array![1.1, 2.0, 3.123, 3.123, 4.5];
        test_monotonic!(data, Monotonic::Rising { strict: false });
    }

    #[test]
    fn test_strict_monotonic_falling_f64() {
        let data: Array1<f64> = array![5.8, 4.123, 3.1, 2.0, 1.0];
        test_monotonic!(data, Monotonic::Falling { strict: true });
    }

    #[test]
    fn test_monotonic_falling_f64() {
        let data: Array1<f64> = array![5.8, 4.123, 3.1, 3.1, 2.0, 1.0];
        test_monotonic!(data, Monotonic::Falling { strict: false });
    }

    #[test]
    fn test_not_monotonic_f64() {
        let data: Array1<f64> = array![1.1, 2.0, 3.123, 3.120, 4.5];
        test_monotonic!(data, Monotonic::NotMonotonic);
    }

    // test with i32
    #[test]
    fn test_strict_monotonic_rising_i32() {
        let data: Array1<i32> = array![1, 2, 3, 4, 5];
        test_monotonic!(data, Monotonic::Rising { strict: true });
    }

    #[test]
    fn test_monotonic_rising_i32() {
        let data: Array1<i32> = array![1, 2, 3, 3, 4, 5];
        test_monotonic!(data, Monotonic::Rising { strict: false });
    }

    #[test]
    fn test_strict_monotonic_falling_i32() {
        let data: Array1<i32> = array![5, 4, 3, 2, 1];
        test_monotonic!(data, Monotonic::Falling { strict: true });
    }

    #[test]
    fn test_monotonic_falling_i32() {
        let data: Array1<i32> = array![5, 4, 3, 3, 2, 1];
        test_monotonic!(data, Monotonic::Falling { strict: false });
    }

    #[test]
    fn test_not_monotonic_i32() {
        let data: Array1<i32> = array![1, 2, 3, 2, 4, 5];
        test_monotonic!(data, Monotonic::NotMonotonic);
    }

    #[test]
    fn test_ordered_view_on_unordred_array() {
        let data: Array1<i32> = array![5, 4, 3, 2, 1];
        let ordered = data.slice(s![..;-1]);
        test_monotonic!(ordered, Monotonic::Rising { strict: true });
    }

    #[test]
    fn test_starting_flat() {
        let data: Array1<i32> = array![1, 1, 2, 3, 4, 5];
        test_monotonic!(data, Monotonic::Rising { strict: false });
    }

    #[test]
    fn test_flat() {
        let data: Array1<i32> = array![1, 1, 1];
        test_monotonic!(data, Monotonic::NotMonotonic);
    }

    #[test]
    fn test_one_element_array() {
        let data: Array1<i32> = array![1];
        test_monotonic!(data, Monotonic::NotMonotonic);
    }
}