Skip to main content

ferrochart_core/data/
lod.rs

1//! LOD pyramid for OHLC(V) series and the visible-range extremes query.
2//!
3//! Level `k >= 2` merges `2^k` bars into one bucket, stored as `f32` with directed
4//! rounding (high up, low down, the rest to nearest), so the stored `[low, high]`
5//! always contains the true range. Buckets are aligned to the fixed logical index
6//! origin [`ANCHOR`], not to array positions, so `Prepend` never moves existing
7//! buckets. Level 1 is not built.
8//!
9//! Every bucket of level `k > 2` is derived from its two children at level `k - 1`
10//! (level 2 from the raw `f64` bars), both in the full build and in incremental
11//! updates, so the two always produce bit-identical results.
12//!
13
14use super::{DeqColumn, IdxSpan};
15use crate::error::{Error, Result};
16
17/// Fixed logical index origin for LOD buckets and GPU chunks. Logical indices must stay
18/// above it.
19pub const ANCHOR: i64 = -(1 << 40);
20
21/// Lowest LOD level that is built (level 1 is skipped).
22pub const MIN_LOD_LEVEL: u8 = 2;
23
24/// Bucket number of logical index `i` at level `k`.
25pub(crate) fn bucket_of(i: i64, k: u32) -> i64 {
26    (i - ANCHOR) >> k
27}
28
29/// First logical index of bucket `b` at level `k`.
30pub(crate) fn bucket_start(b: i64, k: u32) -> i64 {
31    ANCHOR + (b << k)
32}
33
34/// `f64 -> f32`, rounded towards +∞.
35pub(crate) fn f32_up(x: f64) -> f32 {
36    let f = x as f32;
37    if f64::from(f) < x { f.next_up() } else { f }
38}
39
40/// `f64 -> f32`, rounded towards -∞.
41pub(crate) fn f32_down(x: f64) -> f32 {
42    let f = x as f32;
43    if f64::from(f) > x { f.next_down() } else { f }
44}
45
46/// Converts a non-negative `i64` position to `usize` (0 if negative).
47fn pos(i: i64) -> usize {
48    usize::try_from(i).unwrap_or(0)
49}
50
51/// Borrowed level-0 data of a series.
52#[derive(Clone, Copy)]
53pub(crate) struct Raw<'a> {
54    pub first: i64,
55    pub open: &'a [f64],
56    pub high: &'a [f64],
57    pub low: &'a [f64],
58    pub close: &'a [f64],
59    pub volume: Option<&'a [f64]>,
60}
61
62impl Raw<'_> {
63    pub fn end(&self) -> i64 {
64        self.first + i64::try_from(self.open.len()).unwrap_or(i64::MAX)
65    }
66}
67
68#[derive(Clone, Copy, Default, Debug, PartialEq)]
69struct Bucket {
70    open: f32,
71    high: f32,
72    low: f32,
73    close: f32,
74    volume: f32,
75}
76
77/// One LOD level: buckets `first..first + len` in `f32` columns.
78#[derive(Clone, Debug)]
79pub(crate) struct LodLevel {
80    pub first: i64,
81    pub open: DeqColumn<f32>,
82    pub high: DeqColumn<f32>,
83    pub low: DeqColumn<f32>,
84    pub close: DeqColumn<f32>,
85    pub volume: Option<DeqColumn<f32>>,
86}
87
88impl LodLevel {
89    pub fn len(&self) -> usize {
90        self.open.len()
91    }
92
93    pub fn end(&self) -> i64 {
94        self.first + i64::try_from(self.len()).unwrap_or(i64::MAX)
95    }
96
97    fn contains(&self, b: i64) -> bool {
98        b >= self.first && b < self.end()
99    }
100
101    fn get(&self, b: i64) -> Bucket {
102        let p = pos(b - self.first);
103        Bucket {
104            open: self.open[p],
105            high: self.high[p],
106            low: self.low[p],
107            close: self.close[p],
108            volume: self.volume.as_ref().map_or(0.0, |v| v[p]),
109        }
110    }
111
112    fn set(&mut self, b: i64, x: Bucket) {
113        let p = pos(b - self.first);
114        self.open[p] = x.open;
115        self.high[p] = x.high;
116        self.low[p] = x.low;
117        self.close[p] = x.close;
118        if let Some(v) = self.volume.as_mut() {
119            v[p] = x.volume;
120        }
121    }
122
123    /// Builds buckets `first..end` with `f`, allocating exactly.
124    fn build(first: i64, end: i64, has_volume: bool, f: impl Fn(i64) -> Bucket) -> Result<Self> {
125        let n = pos(end - first);
126        let mut cols: [Vec<f32>; 5] = Default::default();
127        for c in &mut cols {
128            c.try_reserve_exact(n).map_err(|_| Error::OutOfMemory)?;
129        }
130        for b in first..end {
131            let x = f(b);
132            cols[0].push(x.open);
133            cols[1].push(x.high);
134            cols[2].push(x.low);
135            cols[3].push(x.close);
136            if has_volume {
137                cols[4].push(x.volume);
138            }
139        }
140        let [o, h, l, c, v] = cols;
141        Ok(Self {
142            first,
143            open: DeqColumn::from_vec(o),
144            high: DeqColumn::from_vec(h),
145            low: DeqColumn::from_vec(l),
146            close: DeqColumn::from_vec(c),
147            volume: has_volume.then(|| DeqColumn::from_vec(v)),
148        })
149    }
150
151    fn columns_mut(&mut self) -> impl Iterator<Item = &mut DeqColumn<f32>> {
152        [
153            Some(&mut self.open),
154            Some(&mut self.high),
155            Some(&mut self.low),
156            Some(&mut self.close),
157            self.volume.as_mut(),
158        ]
159        .into_iter()
160        .flatten()
161    }
162
163    fn reserve(&mut self, front: usize, back: usize) -> Result<()> {
164        for c in self.columns_mut() {
165            c.reserve_front(front)?;
166            c.reserve_back(back)?;
167        }
168        Ok(())
169    }
170
171    /// Extends the level with zero buckets to cover `first..end`. Infallible after
172    /// a matching [`reserve`](Self::reserve).
173    fn cover(&mut self, first: i64, end: i64) {
174        let front = pos(self.first - first);
175        let back = pos(end - self.end());
176        for c in self.columns_mut() {
177            // Space was reserved, so these do not allocate and cannot fail.
178            let _ = c.grow_front(front, 0.0);
179            let _ = c.grow_back(back, 0.0);
180        }
181        self.first = self.first.min(first);
182    }
183
184    fn heap_bytes(&self) -> usize {
185        let cols = 4 + usize::from(self.volume.is_some());
186        cols * self.len() * core::mem::size_of::<f32>()
187    }
188}
189
190/// Bucket `b` of level 2, computed from the raw bars.
191fn raw_bucket(raw: &Raw<'_>, b: i64) -> Bucket {
192    let lo = bucket_start(b, 2).max(raw.first);
193    let hi = bucket_start(b + 1, 2).min(raw.end());
194    let (s, e) = (pos(lo - raw.first), pos(hi - raw.first));
195    let mut high = f64::NEG_INFINITY;
196    let mut low = f64::INFINITY;
197    let mut volume = 0.0;
198    // Gaps (NaN) are skipped: `max`/`min` ignore NaN, and open/close are the
199    // first and last finite ones (NaN if the bucket is all gaps).
200    let mut open = f64::NAN;
201    let mut close = f64::NAN;
202    for p in s..e {
203        high = high.max(raw.high[p]);
204        low = low.min(raw.low[p]);
205        if open.is_nan() {
206            open = raw.open[p];
207        }
208        if !raw.close[p].is_nan() {
209            close = raw.close[p];
210        }
211        if let Some(v) = raw.volume
212            && !v[p].is_nan()
213        {
214            volume += v[p];
215        }
216    }
217    Bucket {
218        open: open as f32,
219        high: f32_up(high),
220        low: f32_down(low),
221        close: close as f32,
222        volume: volume as f32,
223    }
224}
225
226/// Bucket `b` of level `k + 1`, computed from its children at level `k`.
227fn child_bucket(child: &LodLevel, b: i64) -> Bucket {
228    let (c0, c1) = (2 * b, 2 * b + 1);
229    match (child.contains(c0), child.contains(c1)) {
230        (true, true) => {
231            let (x, y) = (child.get(c0), child.get(c1));
232            Bucket {
233                open: if x.open.is_nan() { y.open } else { x.open },
234                high: x.high.max(y.high),
235                low: x.low.min(y.low),
236                close: if y.close.is_nan() { x.close } else { y.close },
237                volume: (f64::from(x.volume) + f64::from(y.volume)) as f32,
238            }
239        }
240        (true, false) => child.get(c0),
241        (false, true) => child.get(c1),
242        (false, false) => Bucket::default(),
243    }
244}
245
246/// The LOD pyramid of one OHLC series. `levels[i]` is level `i + 2`.
247#[derive(Clone, Debug, Default)]
248pub(crate) struct Lod {
249    levels: Vec<LodLevel>,
250}
251
252impl Lod {
253    /// Full build from the raw data. O(n).
254    pub fn build(raw: &Raw<'_>) -> Result<Self> {
255        let mut lod = Self::default();
256        if raw.open.is_empty() {
257            return Ok(lod);
258        }
259        let has_volume = raw.volume.is_some();
260        let first = bucket_of(raw.first, 2);
261        let end = bucket_of(raw.end() - 1, 2) + 1;
262        lod.levels.try_reserve(24).map_err(|_| Error::OutOfMemory)?;
263        lod.levels
264            .push(LodLevel::build(first, end, has_volume, |b| {
265                raw_bucket(raw, b)
266            })?);
267        while lod.add_level_if_needed(raw.end() - 1)? {}
268        Ok(lod)
269    }
270
271    /// Number of built levels; the highest level is `MIN_LOD_LEVEL + count - 1`.
272    #[cfg(test)]
273    pub fn level_count(&self) -> usize {
274        self.levels.len()
275    }
276
277    /// Level `k` (`k >= 2`), if built.
278    pub fn level(&self, k: u8) -> Option<&LodLevel> {
279        let i = usize::from(k.checked_sub(MIN_LOD_LEVEL)?);
280        self.levels.get(i)
281    }
282
283    /// Highest built level, or `None` if there are no levels.
284    pub fn max_level(&self) -> Option<u8> {
285        let n = u8::try_from(self.levels.len()).ok()?;
286        n.checked_sub(1).map(|top| top + MIN_LOD_LEVEL)
287    }
288
289    /// Adds one level above the current top if the top still has more than two
290    /// buckets. Returns whether a level was added.
291    fn add_level_if_needed(&mut self, last_index: i64) -> Result<bool> {
292        let Some(top) = self.levels.last() else {
293            return Ok(false);
294        };
295        if top.len() <= 2 {
296            return Ok(false);
297        }
298        let k = u32::try_from(self.levels.len()).unwrap_or(u32::MAX) + 2; // new level
299        let first = top.first >> 1;
300        let end = bucket_of(last_index, k) + 1;
301        let has_volume = top.volume.is_some();
302        let level = LodLevel::build(first, end, has_volume, |b| child_bucket(top, b))?;
303        self.levels.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
304        self.levels.push(level);
305        Ok(true)
306    }
307
308    /// Reserves room so that [`update`](Self::update) for data covering
309    /// `new_first..new_end` cannot fail.
310    pub fn reserve(&mut self, new_first: i64, new_end: i64) -> Result<()> {
311        for (i, level) in self.levels.iter_mut().enumerate() {
312            let k = u32::try_from(i).unwrap_or(u32::MAX) + 2;
313            let first = bucket_of(new_first, k);
314            let end = bucket_of(new_end - 1, k) + 1;
315            level.reserve(pos(level.first - first), pos(end - level.end()))?;
316        }
317        Ok(())
318    }
319
320    /// Updates the pyramid after the slots in `changed` were written. `raw` is the
321    /// data after the change and may extend beyond the previous data on either
322    /// side (append/prepend). O(`changed.len()` + log n).
323    ///
324    /// Must be preceded by a successful [`reserve`](Self::reserve) for the new
325    /// extent; the update itself then cannot fail. Adding a new top level may
326    /// allocate; if that fails the pyramid simply keeps fewer levels.
327    pub fn update(&mut self, raw: &Raw<'_>, changed: IdxSpan) {
328        if raw.open.is_empty() || changed.is_empty() {
329            return;
330        }
331        if self.levels.is_empty() {
332            if let Ok(lod) = Self::build(raw) {
333                *self = lod;
334            }
335            return;
336        }
337        let last = raw.end() - 1;
338        for i in 0..self.levels.len() {
339            let k = u32::try_from(i).unwrap_or(u32::MAX) + 2;
340            let (below, rest) = self.levels.split_at_mut(i);
341            let level = &mut rest[0];
342            level.cover(bucket_of(raw.first, k), bucket_of(last, k) + 1);
343            let from = bucket_of(changed.start.max(raw.first), k);
344            let to = bucket_of((changed.end - 1).min(last), k) + 1;
345            for b in from..to {
346                let x = match below.last() {
347                    None => raw_bucket(raw, b),
348                    Some(child) => child_bucket(child, b),
349                };
350                level.set(b, x);
351            }
352        }
353        while let Ok(true) = self.add_level_if_needed(last) {}
354    }
355
356    /// Drops the buckets past the data after bars were removed from its end
357    /// (`raw` is the data after the removal) and recomputes the last bucket of
358    /// every level. Keeps the capacity; never allocates.
359    pub fn truncate(&mut self, raw: &Raw<'_>) {
360        if raw.open.is_empty() {
361            self.levels.clear();
362            return;
363        }
364        let last = raw.end() - 1;
365        for i in 0..self.levels.len() {
366            let k = u32::try_from(i).unwrap_or(u32::MAX) + 2;
367            let (below, rest) = self.levels.split_at_mut(i);
368            let level = &mut rest[0];
369            let b = bucket_of(last, k);
370            let extra = pos(level.end() - (b + 1));
371            for c in level.columns_mut() {
372                c.truncate_ends(0, extra);
373            }
374            if level.contains(b) {
375                let x = match below.last() {
376                    None => raw_bucket(raw, b),
377                    Some(child) => child_bucket(child, b),
378                };
379                level.set(b, x);
380            }
381        }
382    }
383
384    /// Minimum low and maximum high over logical indices `from..to` (clamped to the
385    /// data), or `None` if that range holds no data. O(log n): raw bars at both
386    /// ends, the largest aligned buckets in the middle. The result always contains
387    /// the true extremes (directed rounding).
388    pub fn extremes(&self, raw: &Raw<'_>, from: i64, to: i64) -> Option<(f64, f64)> {
389        let a = from.max(raw.first);
390        let b = to.min(raw.end());
391        if a >= b {
392            return None;
393        }
394        let mut lo = f64::INFINITY;
395        let mut hi = f64::NEG_INFINITY;
396        let mut scan = |s: i64, e: i64| {
397            for p in pos(s - raw.first)..pos(e - raw.first) {
398                lo = lo.min(raw.low[p]);
399                hi = hi.max(raw.high[p]);
400            }
401        };
402        let a2 = bucket_start(bucket_of(a + 3, 2), 2); // align up to a level-2 boundary
403        let b2 = bucket_start(bucket_of(b, 2), 2); // align down
404        if self.levels.is_empty() || a2 >= b2 {
405            scan(a, b);
406            return Some((lo, hi));
407        }
408        scan(a, a2);
409        scan(b2, b);
410
411        let mut take = |level: &LodLevel, x: i64| {
412            let bucket = level.get(x);
413            lo = lo.min(f64::from(bucket.low));
414            hi = hi.max(f64::from(bucket.high));
415        };
416        let (mut l, mut r) = (bucket_of(a2, 2), bucket_of(b2, 2));
417        for (i, level) in self.levels.iter().enumerate() {
418            if i + 1 == self.levels.len() {
419                for x in l..r {
420                    take(level, x);
421                }
422                break;
423            }
424            if l & 1 == 1 {
425                take(level, l);
426                l += 1;
427            }
428            if r & 1 == 1 {
429                r -= 1;
430                take(level, r);
431            }
432            if l >= r {
433                break;
434            }
435            l >>= 1;
436            r >>= 1;
437        }
438        Some((lo, hi))
439    }
440
441    /// Heap bytes held by the level columns.
442    pub fn heap_bytes(&self) -> usize {
443        self.levels.iter().map(LodLevel::heap_bytes).sum()
444    }
445}
446
447#[cfg(test)]
448#[allow(clippy::float_cmp)] // exact values are the point of these tests
449mod tests {
450    use super::*;
451    use proptest::prelude::*;
452
453    struct Data {
454        first: i64,
455        o: Vec<f64>,
456        h: Vec<f64>,
457        l: Vec<f64>,
458        c: Vec<f64>,
459        v: Vec<f64>,
460    }
461
462    impl Data {
463        fn raw(&self) -> Raw<'_> {
464            Raw {
465                first: self.first,
466                open: &self.o,
467                high: &self.h,
468                low: &self.l,
469                close: &self.c,
470                volume: Some(&self.v),
471            }
472        }
473    }
474
475    fn data(first: i64, prices: &[(f64, f64)]) -> Data {
476        // (center, half-range) -> bar
477        let mut d = Data {
478            first,
479            o: vec![],
480            h: vec![],
481            l: vec![],
482            c: vec![],
483            v: vec![],
484        };
485        for &(m, r) in prices {
486            d.o.push(m - r / 3.0);
487            d.c.push(m + r / 4.0);
488            d.h.push(m + r);
489            d.l.push(m - r);
490            d.v.push(r + 0.5);
491        }
492        d
493    }
494
495    fn bars() -> impl Strategy<Value = (i64, Vec<(f64, f64)>)> {
496        (
497            -300i64..300,
498            prop::collection::vec((-1e6f64..1e6, 0.0f64..1e3), 0..600),
499        )
500    }
501
502    /// Checks every bucket of every level against the raw data.
503    fn check_pyramid(lod: &Lod, d: &Data) -> std::result::Result<(), TestCaseError> {
504        let raw = d.raw();
505        for (i, level) in lod.levels.iter().enumerate() {
506            let k = u32::try_from(i).unwrap() + 2;
507            prop_assert_eq!(level.first, bucket_of(raw.first, k));
508            prop_assert_eq!(level.end(), bucket_of(raw.end() - 1, k) + 1);
509            for b in level.first..level.end() {
510                let s = pos(bucket_start(b, k).max(raw.first) - raw.first);
511                let e = pos(bucket_start(b + 1, k).min(raw.end()) - raw.first);
512                let max = d.h[s..e].iter().copied().fold(f64::NEG_INFINITY, f64::max);
513                let min = d.l[s..e].iter().copied().fold(f64::INFINITY, f64::min);
514                let x = level.get(b);
515                prop_assert!(f64::from(x.high) >= max && f64::from(x.high.next_down()) < max);
516                prop_assert!(f64::from(x.low) <= min && f64::from(x.low.next_up()) > min);
517                prop_assert_eq!(x.open, d.o[s] as f32);
518                prop_assert_eq!(x.close, d.c[e - 1] as f32);
519                prop_assert!(x.low <= x.open.min(x.close) && x.open.max(x.close) <= x.high);
520            }
521        }
522        if let Some(top) = lod.levels.last() {
523            prop_assert!(top.len() <= 2);
524        }
525        Ok(())
526    }
527
528    #[test]
529    fn directed_rounding() {
530        let x = 0.1_f64; // not representable in f32
531        assert!(f64::from(f32_up(x)) > x && f64::from(f32_down(x)) < x);
532        assert_eq!(f32_up(0.5), 0.5);
533        assert_eq!(f32_down(0.5), 0.5);
534        assert_eq!(f32_up(f64::MAX), f32::INFINITY);
535    }
536
537    #[test]
538    fn tiny_series_has_one_level() {
539        let d = data(0, &[(10.0, 1.0)]);
540        let lod = Lod::build(&d.raw()).unwrap();
541        assert_eq!(lod.level_count(), 1);
542        assert_eq!(lod.max_level(), Some(2));
543        assert_eq!(lod.extremes(&d.raw(), -5, 5), Some((9.0, 11.0)));
544        assert_eq!(lod.extremes(&d.raw(), 1, 5), None);
545    }
546
547    proptest! {
548        #[test]
549        fn full_build_is_correct((first, prices) in bars()) {
550            let d = data(first, &prices);
551            let lod = Lod::build(&d.raw()).unwrap();
552            check_pyramid(&lod, &d)?;
553        }
554
555        /// Incremental appends, updates and prepends give exactly the full build.
556        #[test]
557        fn incremental_equals_full(
558            (first, mut prices) in bars(),
559            steps in prop::collection::vec((0u8..3, 1usize..40), 0..30),
560        ) {
561            let n = prices.len();
562            if n == 0 { return Ok(()); }
563            // Start from a middle slice, then grow it on both sides.
564            let mut lo = n / 2;
565            let mut hi = lo + 1;
566            let mut cur = data(first + i64::try_from(lo).unwrap(), &prices[lo..hi]);
567            let mut lod = Lod::build(&cur.raw()).unwrap();
568            for (kind, count) in steps {
569                let old = (lo, hi);
570                match kind {
571                    0 => hi = (hi + count).min(n),
572                    1 => lo = lo.saturating_sub(count),
573                    _ => {}
574                }
575                if kind == 2 {
576                    // update_last: move the last bar (persistently).
577                    prices[hi - 1].0 += 5.0;
578                }
579                let next = data(first + i64::try_from(lo).unwrap(), &prices[lo..hi]);
580                let to_idx = |p: usize| first + i64::try_from(p).unwrap();
581                let changed = match kind {
582                    0 => IdxSpan { start: to_idx(old.1 - 1), end: to_idx(hi) },
583                    1 => IdxSpan { start: to_idx(lo), end: to_idx(old.0) },
584                    _ => IdxSpan { start: to_idx(hi - 1), end: to_idx(hi) },
585                };
586                let raw = next.raw();
587                lod.reserve(raw.first, raw.end()).unwrap();
588                lod.update(&raw, changed);
589                cur = next;
590                let full = Lod::build(&cur.raw()).unwrap();
591                prop_assert_eq!(lod.levels.len(), full.levels.len());
592                for (a, b) in lod.levels.iter().zip(&full.levels) {
593                    prop_assert_eq!(a.first, b.first);
594                    prop_assert_eq!(&a.high[..], &b.high[..]);
595                    prop_assert_eq!(&a.low[..], &b.low[..]);
596                    prop_assert_eq!(&a.open[..], &b.open[..]);
597                    prop_assert_eq!(&a.close[..], &b.close[..]);
598                    prop_assert_eq!(a.volume.as_deref(), b.volume.as_deref());
599                }
600            }
601            check_pyramid(&lod, &cur)?;
602        }
603
604        /// The extremes query always contains the true extremes and is at most one
605        /// f32 ulp away from them.
606        #[test]
607        fn extremes_contain_truth((first, prices) in bars(), a in -400i64..1000, len in 0i64..1000) {
608            let d = data(first, &prices);
609            let lod = Lod::build(&d.raw()).unwrap();
610            let raw = d.raw();
611            let (s, e) = (a.max(raw.first), (a + len).min(raw.end()));
612            let got = lod.extremes(&raw, a, a + len);
613            if s >= e {
614                prop_assert_eq!(got, None);
615            } else {
616                let (lo, hi) = got.unwrap();
617                let (ps, pe) = (pos(s - raw.first), pos(e - raw.first));
618                let max = d.h[ps..pe].iter().copied().fold(f64::NEG_INFINITY, f64::max);
619                let min = d.l[ps..pe].iter().copied().fold(f64::INFINITY, f64::min);
620                prop_assert!(hi >= max && lo <= min);
621                prop_assert!(hi <= f64::from(f32_up(max)) && lo >= f64::from(f32_down(min)));
622            }
623        }
624
625        /// Prepending never changes existing buckets except the shared boundary one.
626        #[test]
627        fn prepend_keeps_old_buckets((first, prices) in bars(), cut in 0usize..600) {
628            let n = prices.len();
629            let cut = cut.min(n);
630            if cut == n { return Ok(()); }
631            let old = data(first + i64::try_from(cut).unwrap(), &prices[cut..]);
632            let new = data(first, &prices);
633            let before = Lod::build(&old.raw()).unwrap();
634            let after = Lod::build(&new.raw()).unwrap();
635            for (i, level) in before.levels.iter().enumerate() {
636                let k = u32::try_from(i).unwrap() + 2;
637                let boundary = bucket_of(old.first, k);
638                for b in (boundary + 1)..level.end() {
639                    prop_assert_eq!(level.get(b), after.levels[i].get(b));
640                }
641            }
642        }
643    }
644}