Skip to main content

crisol_core/data/
pyramid.rs

1//! A lazily built min/max pyramid for out-of-core range queries.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use super::column::CellValue;
8use super::source::{DataError, DataSource};
9
10/// One block of a level: its x span and the y minimum/maximum in that span.
11#[derive(Clone, Copy, Debug, PartialEq)]
12/// # Example
13///
14/// ```
15/// use crisol_core::data::LodTile;
16/// ```
17pub struct LodTile {
18    /// First x in the block.
19    pub x_min: f64,
20    /// Last x in the block.
21    pub x_max: f64,
22    /// Smallest y in the block.
23    pub y_min: f64,
24    /// Largest y in the block.
25    pub y_max: f64,
26    /// First row (inclusive).
27    pub row_start: usize,
28    /// Last row (exclusive).
29    pub row_end: usize,
30}
31
32impl LodTile {
33    /// Four points that outline the tile for a line plot.
34    pub fn outline(self) -> [[f64; 2]; 4] {
35        [
36            [self.x_min, self.y_min],
37            [self.x_min, self.y_max],
38            [self.x_max, self.y_min],
39            [self.x_max, self.y_max],
40        ]
41    }
42}
43
44/// A min/max pyramid over a paged source. Levels are built on first use and blocks are
45/// cached, so a plot asks only for the tiles its viewport needs.
46/// # Example
47///
48/// ```
49/// use crisol_core::data::MinMaxPyramid;
50/// ```
51pub struct MinMaxPyramid {
52    source: Arc<dyn DataSource>,
53    x_column: usize,
54    y_column: usize,
55    block: usize,
56    levels: RefCell<Vec<Option<Vec<LodTile>>>>,
57    cache: RefCell<HashMap<(usize, usize), LodTile>>,
58    revision: u64,
59}
60
61impl MinMaxPyramid {
62    /// A pyramid over two columns of `source`, with `block` rows per tile.
63    pub fn new(source: Arc<dyn DataSource>, x_column: usize, y_column: usize, block: usize) -> Self {
64        Self {
65            source,
66            x_column,
67            y_column,
68            block: block.max(2),
69            levels: RefCell::new(Vec::new()),
70            cache: RefCell::new(HashMap::new()),
71            revision: 0,
72        }
73    }
74
75    /// The number of rows in the source.
76    pub fn row_count(&self) -> usize {
77        self.source.row_count()
78    }
79
80    /// The block size at level 0.
81    pub fn block(&self) -> usize {
82        self.block
83    }
84
85    /// The source revision.
86    pub fn revision(&self) -> u64 {
87        self.revision
88    }
89
90    /// Invalidate every tile after the source changed.
91    pub fn invalidate(&mut self) {
92        self.levels.get_mut().clear();
93        self.cache.get_mut().clear();
94        self.revision = self.revision.wrapping_add(1);
95    }
96
97    /// The tile at `level` and `index`, building the level when needed.
98    ///
99    /// # Errors
100    /// When a source page cannot be read.
101    pub fn tile(&self, level: usize, index: usize) -> Result<Option<LodTile>, DataError> {
102        if let Some(tile) = self.cache.borrow().get(&(level, index)) {
103            return Ok(Some(*tile));
104        }
105        // A level past the width of `usize` has no tiles; building it would shift out of
106        // range and reserve `level` empty slots.
107        if self
108            .block
109            .checked_shl(u32::try_from(level).unwrap_or(u32::MAX))
110            .is_none_or(|block| block >> level != self.block)
111        {
112            return Ok(None);
113        }
114        self.build_level(level)?;
115        let tile = self
116            .levels
117            .borrow()
118            .get(level)
119            .and_then(|level| level.as_ref())
120            .and_then(|tiles| tiles.get(index).copied());
121        if let Some(tile) = tile {
122            self.cache.borrow_mut().insert((level, index), tile);
123        }
124        Ok(tile)
125    }
126
127    /// Tiles that cover `range` at a level chosen to fit `budget`.
128    ///
129    /// # Errors
130    /// When a source page cannot be read.
131    pub fn range(&self, range: std::ops::Range<usize>, budget: usize) -> Result<Vec<LodTile>, DataError> {
132        let start = range.start.min(self.row_count());
133        let end = range.end.min(self.row_count()).max(start);
134        if end <= start {
135            return Ok(Vec::new());
136        }
137        let span = end - start;
138        let mut level = 0;
139        while (span / (self.block << level)).max(1) > budget.max(1) {
140            level += 1;
141        }
142        self.build_level(level)?;
143        let mut tiles = Vec::new();
144        if let Some(Some(level_tiles)) = self.levels.borrow().get(level) {
145            for (index, tile) in level_tiles.iter().enumerate() {
146                if tile.row_end > start && tile.row_start < end {
147                    tiles.push(*tile);
148                    if tiles.len() >= budget {
149                        break;
150                    }
151                }
152                let _ = index;
153            }
154        }
155        Ok(tiles)
156    }
157
158    /// A decimated polyline with four points per tile.
159    ///
160    /// # Errors
161    /// When a source page cannot be read.
162    pub fn polyline(&self, range: std::ops::Range<usize>, budget: usize) -> Result<Vec<[f64; 2]>, DataError> {
163        let mut points = Vec::new();
164        for tile in self.range(range, budget)? {
165            points.extend(tile.outline());
166        }
167        Ok(points)
168    }
169
170    /// Tiles whose x span intersects `[x_min, x_max]`, at the finest level that fits
171    /// `budget` tiles. This is the zoom-driven lookup a streaming plot uses: the row
172    /// range is not known, only the visible data range.
173    ///
174    /// # Errors
175    /// When a source page cannot be read.
176    pub fn tiles_in_x(&self, x_min: f64, x_max: f64, budget: usize) -> Result<Vec<LodTile>, DataError> {
177        if !x_min.is_finite() || !x_max.is_finite() || x_max <= x_min {
178            return Ok(Vec::new());
179        }
180        let budget = budget.max(1);
181        let mut level = 0;
182        loop {
183            self.build_level(level)?;
184            let tiles: Vec<LodTile> = self
185                .levels
186                .borrow()
187                .get(level)
188                .and_then(|level| level.as_ref())
189                .map(|tiles| {
190                    tiles
191                        .iter()
192                        .copied()
193                        .filter(|tile| tile.x_max >= x_min && tile.x_min <= x_max)
194                        .collect()
195                })
196                .unwrap_or_default();
197            if tiles.len() <= budget || tiles.len() <= 1 {
198                return Ok(tiles);
199            }
200            level += 1;
201        }
202    }
203
204    /// A decimated polyline for a visible x range.
205    ///
206    /// # Errors
207    /// When a source page cannot be read.
208    pub fn polyline_in_x(&self, x_min: f64, x_max: f64, budget: usize) -> Result<Vec<[f64; 2]>, DataError> {
209        let mut points = Vec::new();
210        for tile in self.tiles_in_x(x_min, x_max, budget)? {
211            points.extend(tile.outline());
212        }
213        Ok(points)
214    }
215
216    fn build_level(&self, level: usize) -> Result<(), DataError> {
217        if self.levels.borrow().get(level).is_some_and(Option::is_some) {
218            return Ok(());
219        }
220        let block = self.block << level;
221        let rows = self.row_count();
222        let mut tiles = Vec::with_capacity(rows.div_ceil(block).max(1));
223        let mut start = 0;
224        while start < rows {
225            let end = (start + block).min(rows);
226            let page = self.source.read_range(start..end)?;
227            let mut x_min = f64::INFINITY;
228            let mut x_max = f64::NEG_INFINITY;
229            let mut y_min = f64::INFINITY;
230            let mut y_max = f64::NEG_INFINITY;
231            for row in 0..page.row_count() {
232                let x = numeric(page.cell(row, self.x_column));
233                let y = numeric(page.cell(row, self.y_column));
234                if let (Some(x), Some(y)) = (x, y) {
235                    x_min = x_min.min(x);
236                    x_max = x_max.max(x);
237                    y_min = y_min.min(y);
238                    y_max = y_max.max(y);
239                }
240            }
241            if x_min.is_finite() && y_min.is_finite() {
242                tiles.push(LodTile {
243                    x_min,
244                    x_max,
245                    y_min,
246                    y_max,
247                    row_start: start,
248                    row_end: end,
249                });
250            }
251            start = end;
252        }
253        let mut levels = self.levels.borrow_mut();
254        while levels.len() <= level {
255            levels.push(None);
256        }
257        if let Some(slot) = levels.get_mut(level) {
258            *slot = Some(tiles);
259        }
260        Ok(())
261    }
262}
263
264fn numeric(cell: CellValue<'_>) -> Option<f64> {
265    match cell {
266        CellValue::Float(value) => value.is_finite().then_some(value),
267        CellValue::Int(value) => Some(value as f64),
268        CellValue::Date(value) | CellValue::Time(value) => Some(value as f64),
269        _ => None,
270    }
271}
272
273impl std::fmt::Debug for MinMaxPyramid {
274    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        formatter
276            .debug_struct("MinMaxPyramid")
277            .field("rows", &self.row_count())
278            .field("block", &self.block)
279            .finish_non_exhaustive()
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use crate::data::{Column, Dataset, MemorySource};
287
288    fn source() -> Arc<dyn DataSource> {
289        let x: Vec<f64> = (0..10_000).map(|index| index as f64 * 0.01).collect();
290        let y: Vec<f64> = x.iter().map(|x| x.sin()).collect();
291        Arc::new(MemorySource::new(Dataset::from_columns([
292            Column::floats("t", x),
293            Column::floats("v", y),
294        ])))
295    }
296
297    #[test]
298    fn tiles_keep_the_extrema_and_outline() {
299        let pyramid = MinMaxPyramid::new(source(), 0, 1, 256);
300        let tile = pyramid.tile(0, 0).expect("read").expect("tile");
301        assert!(tile.x_min <= tile.x_max);
302        assert!(tile.y_min <= tile.y_max);
303        assert_eq!(tile.outline().len(), 4);
304        assert_eq!(tile.row_start, 0);
305        assert_eq!(tile.row_end, 256);
306    }
307
308    #[test]
309    fn a_range_chooses_a_level_within_the_budget() {
310        let pyramid = MinMaxPyramid::new(source(), 0, 1, 64);
311        let tiles = pyramid.range(0..10_000, 32).expect("range");
312        assert!(!tiles.is_empty());
313        assert!(tiles.len() <= 32);
314        let points = pyramid.polyline(0..10_000, 32).expect("polyline");
315        assert_eq!(points.len(), tiles.len() * 4);
316    }
317
318    #[test]
319    fn an_x_range_selects_the_finest_tiles_that_fit_the_budget() {
320        let pyramid = MinMaxPyramid::new(source(), 0, 1, 64);
321        let tiles = pyramid.tiles_in_x(10.0, 20.0, 8).expect("tiles");
322        assert!(!tiles.is_empty());
323        assert!(tiles.len() <= 8);
324        assert!(tiles.iter().all(|tile| tile.x_max >= 10.0 && tile.x_min <= 20.0));
325        let points = pyramid.polyline_in_x(10.0, 20.0, 8).expect("line");
326        assert_eq!(points.len(), tiles.len() * 4);
327    }
328
329    #[test]
330    fn x_ranges_handle_empty_and_non_finite_queries() {
331        let pyramid = MinMaxPyramid::new(source(), 0, 1, 64);
332        assert!(pyramid.tiles_in_x(f64::NAN, 1.0, 4).expect("nan").is_empty());
333        assert!(pyramid.tiles_in_x(5.0, 5.0, 4).expect("empty").is_empty());
334        assert!(pyramid.tiles_in_x(1.0e9, 2.0e9, 4).expect("outside").is_empty());
335        assert!(pyramid.polyline_in_x(5.0, 5.0, 4).expect("line").is_empty());
336        let one = pyramid.tiles_in_x(10.0, 20.0, 0).expect("budget");
337        assert_eq!(one.len(), 1);
338    }
339
340    #[test]
341    fn invalidation_rebuilds() {
342        let mut pyramid = MinMaxPyramid::new(source(), 0, 1, 64);
343        let _ = pyramid.tile(0, 0).expect("tile");
344        let revision = pyramid.revision();
345        pyramid.invalidate();
346        assert_ne!(pyramid.revision(), revision);
347        assert!(pyramid.tile(0, 0).expect("tile").is_some());
348    }
349}