ruviz 0.2.0

High-performance 2D plotting library for Rust
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! Simple DataShader implementation without parallel features
//! This will be used to make tests pass initially, then enhanced

use crate::core::error::{PlottingError, Result};
use crate::core::types::{BoundingBox, Point2f};
use std::sync::atomic::{AtomicU32, Ordering};

/// Simple DataShader canvas for aggregation
pub struct DataShaderCanvas {
    width: usize,
    height: usize,
    canvas: Vec<AtomicU32>,
    bounds: BoundingBox,
    total_points: u64,
}

impl DataShaderCanvas {
    /// Create new DataShader canvas
    pub fn new(width: usize, height: usize) -> Self {
        let canvas_size = width * height;
        let canvas = (0..canvas_size).map(|_| AtomicU32::new(0)).collect();

        Self {
            width,
            height,
            canvas,
            bounds: BoundingBox::new(0.0, 1.0, 0.0, 1.0),
            total_points: 0,
        }
    }

    /// Calculate bounds from a set of points
    pub fn calculate_bounds(points: &[(f64, f64)]) -> Result<BoundingBox> {
        if points.is_empty() {
            return Err(PlottingError::EmptyDataSet);
        }

        let mut min_x = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_y = f64::NEG_INFINITY;

        for &(x, y) in points {
            min_x = min_x.min(x);
            max_x = max_x.max(x);
            min_y = min_y.min(y);
            max_y = max_y.max(y);
        }

        Ok(BoundingBox::new(
            min_x as f32,
            max_x as f32,
            min_y as f32,
            max_y as f32,
        ))
    }

    /// Create a DataShaderCanvas with specific bounds
    pub fn with_bounds(width: usize, height: usize, bounds: BoundingBox) -> Self {
        let canvas_size = width * height;
        let canvas = (0..canvas_size).map(|_| AtomicU32::new(0)).collect();

        Self {
            width,
            height,
            canvas,
            bounds,
            total_points: 0,
        }
    }

    /// Set the world coordinate bounds
    pub fn set_bounds(&mut self, bounds: BoundingBox) {
        self.bounds = bounds;
    }

    /// Get the bounds
    pub fn bounds(&self) -> BoundingBox {
        self.bounds
    }

    /// Get canvas width
    pub fn width(&self) -> usize {
        self.width
    }

    /// Get canvas height  
    pub fn height(&self) -> usize {
        self.height
    }

    /// Clear the canvas
    pub fn clear(&self) {
        for cell in &self.canvas {
            cell.store(0, Ordering::Relaxed);
        }
    }

    /// Convert world coordinates to grid coordinates
    fn world_to_grid(&self, point: &Point2f) -> Option<(usize, usize)> {
        // Check if point is within bounds
        if point.x < self.bounds.min_x
            || point.x > self.bounds.max_x
            || point.y < self.bounds.min_y
            || point.y > self.bounds.max_y
        {
            return None;
        }

        // Convert to grid coordinates
        let x_norm = (point.x - self.bounds.min_x) / (self.bounds.max_x - self.bounds.min_x);
        let y_norm = (point.y - self.bounds.min_y) / (self.bounds.max_y - self.bounds.min_y);

        let grid_x = (x_norm * (self.width - 1) as f32) as usize;
        let grid_y = (y_norm * (self.height - 1) as f32) as usize;

        Some((grid_x, grid_y))
    }

    /// Aggregate points from (x, y) tuples
    pub fn aggregate(&mut self, points: &[(f64, f64)]) {
        // Convert to Point2f first
        let point2f_vec: Vec<Point2f> = points
            .iter()
            .map(|&(x, y)| Point2f::new(x as f32, y as f32))
            .collect();

        self.aggregate_points(&point2f_vec);
    }

    /// Aggregate points
    pub fn aggregate_points(&mut self, points: &[Point2f]) {
        for point in points {
            if let Some((grid_x, grid_y)) = self.world_to_grid(point) {
                let idx = grid_y * self.width + grid_x;
                if idx < self.canvas.len() {
                    self.canvas[idx].fetch_add(1, Ordering::Relaxed);
                }
            }
        }

        self.total_points += points.len() as u64;
    }

    /// Get aggregated count at grid position
    pub fn get_count(&self, grid_x: usize, grid_y: usize) -> Option<u32> {
        if grid_x >= self.width || grid_y >= self.height {
            return None;
        }

        let idx = grid_y * self.width + grid_x;
        Some(self.canvas[idx].load(Ordering::Relaxed))
    }

    /// Get maximum count in the canvas
    pub fn max_count(&self) -> u32 {
        self.canvas
            .iter()
            .map(|cell| cell.load(Ordering::Relaxed))
            .max()
            .unwrap_or(0)
    }

    /// Get statistics about the aggregated data
    pub fn statistics(&self) -> DataShaderStats {
        let counts: Vec<u32> = self
            .canvas
            .iter()
            .map(|cell| cell.load(Ordering::Relaxed))
            .collect();

        let non_zero_counts: Vec<u32> = counts.iter().filter(|&&c| c > 0).cloned().collect();
        let max_count = *non_zero_counts.iter().max().unwrap_or(&0);
        let min_count = *non_zero_counts.iter().min().unwrap_or(&0);
        let total_count: u64 = counts.iter().map(|&c| c as u64).sum();
        let filled_pixels = non_zero_counts.len();

        DataShaderStats {
            total_points: self.total_points,
            filled_pixels,
            total_pixels: self.width * self.height,
            max_count,
            min_count,
            total_count,
            canvas_utilization: filled_pixels as f64 / (self.width * self.height) as f64,
        }
    }

    /// Create image data as simple grayscale
    pub fn to_image_data(&self) -> Vec<u8> {
        let max_count = self.max_count();
        let mut pixels = Vec::with_capacity(self.width * self.height * 4);

        for y in 0..self.height {
            for x in 0..self.width {
                let idx = y * self.width + x;
                let count = self.canvas[idx].load(Ordering::Relaxed);

                // Normalize to grayscale
                let intensity = if max_count > 0 {
                    ((count as f64 / max_count as f64) * 255.0) as u8
                } else {
                    0
                };

                // RGBA
                pixels.push(intensity); // R
                pixels.push(intensity); // G  
                pixels.push(intensity); // B
                pixels.push(255); // A
            }
        }

        pixels
    }
}

/// Statistics about aggregated data
#[derive(Debug, Clone)]
pub struct DataShaderStats {
    pub total_points: u64,
    pub filled_pixels: usize,
    pub total_pixels: usize,
    pub max_count: u32,
    pub min_count: u32,
    pub total_count: u64,
    pub canvas_utilization: f64,
}

/// Simple image representation
pub struct DataShaderImage {
    pub width: usize,
    pub height: usize,
    pub pixels: Vec<u8>,
}

impl DataShaderImage {
    pub fn new(width: usize, height: usize, pixels: Vec<u8>) -> Self {
        Self {
            width,
            height,
            pixels,
        }
    }
}

/// DataShader facade - simple aggregation for massive datasets
pub struct DataShader {
    canvas: DataShaderCanvas,
}

impl Default for DataShader {
    fn default() -> Self {
        Self::new()
    }
}

impl DataShader {
    /// Create new DataShader with default canvas size
    pub fn new() -> Self {
        Self::with_canvas_size(512, 512)
    }

    /// Create DataShader with specific canvas size
    pub fn with_canvas_size(width: usize, height: usize) -> Self {
        Self {
            canvas: DataShaderCanvas::new(width, height),
        }
    }

    /// Check if DataShader should be activated for the given point count
    pub fn should_activate(point_count: usize) -> bool {
        point_count >= 100_000
    }

    /// Create canvas size recommendation based on data points and dimensions
    pub fn create_canvas(point_count: usize, width: usize, height: usize) -> (usize, usize) {
        // For simplicity, just return the given dimensions
        // In a more sophisticated implementation, this could adjust canvas size based on point density
        (width, height)
    }

    fn validate_explicit_bounds(x_min: f64, x_max: f64, y_min: f64, y_max: f64) -> Result<()> {
        if !x_min.is_finite() || !x_max.is_finite() || !y_min.is_finite() || !y_max.is_finite() {
            return Err(PlottingError::InvalidInput(format!(
                "DataShader bounds must be finite, got x=({x_min}, {x_max}), y=({y_min}, {y_max})"
            )));
        }

        if x_min >= x_max || y_min >= y_max {
            return Err(PlottingError::InvalidInput(format!(
                "DataShader bounds must satisfy x_min < x_max and y_min < y_max, got x=({x_min}, {x_max}), y=({y_min}, {y_max})"
            )));
        }

        Ok(())
    }

    /// Set data bounds
    pub fn set_bounds(&mut self, min_x: f64, min_y: f64, max_x: f64, max_y: f64) {
        let bounds = BoundingBox::new(min_x as f32, max_x as f32, min_y as f32, max_y as f32);
        self.canvas.set_bounds(bounds);
    }

    /// Aggregate data points
    pub fn aggregate(&mut self, x_data: &[f64], y_data: &[f64]) -> Result<()> {
        if x_data.len() != y_data.len() {
            return Err(PlottingError::DataLengthMismatch {
                x_len: x_data.len(),
                y_len: y_data.len(),
                series_index: None,
            });
        }

        if x_data.is_empty() {
            return Err(PlottingError::EmptyDataSet);
        }

        // Auto-calculate bounds if not set
        let x_min = x_data.iter().fold(f64::INFINITY, |a, &b| a.min(b));
        let x_max = x_data.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
        let y_min = y_data.iter().fold(f64::INFINITY, |a, &b| a.min(b));
        let y_max = y_data.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));

        self.set_bounds(x_min, y_min, x_max, y_max);

        self.aggregate_with_current_bounds(x_data, y_data)
    }

    /// Aggregate data points using explicit `x_min/x_max/y_min/y_max` bounds
    /// instead of auto-fitting to the data.
    pub fn aggregate_with_bounds(
        &mut self,
        x_data: &[f64],
        y_data: &[f64],
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
    ) -> Result<()> {
        if x_data.len() != y_data.len() {
            return Err(PlottingError::DataLengthMismatch {
                x_len: x_data.len(),
                y_len: y_data.len(),
                series_index: None,
            });
        }

        if x_data.is_empty() {
            return Err(PlottingError::EmptyDataSet);
        }

        Self::validate_explicit_bounds(x_min, x_max, y_min, y_max)?;
        self.set_bounds(x_min, y_min, x_max, y_max);
        self.aggregate_with_current_bounds(x_data, y_data)
    }

    fn aggregate_with_current_bounds(&mut self, x_data: &[f64], y_data: &[f64]) -> Result<()> {
        self.canvas.clear();

        // Create point tuples and aggregate
        let points: Vec<(f64, f64)> = x_data
            .iter()
            .zip(y_data.iter())
            .map(|(&x, &y)| (x, y))
            .collect();
        self.canvas.aggregate(&points);

        Ok(())
    }

    /// Get statistics
    pub fn statistics(&self) -> DataShaderStats {
        self.canvas.statistics()
    }

    /// Render to image data
    pub fn render(&self) -> DataShaderImage {
        let pixels = self.canvas.to_image_data();
        DataShaderImage::new(self.canvas.width(), self.canvas.height(), pixels)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_datashader_canvas_creation() {
        let canvas = DataShaderCanvas::new(800, 600);
        assert_eq!(canvas.width(), 800);
        assert_eq!(canvas.height(), 600);
    }

    #[test]
    fn test_point_aggregation() {
        let mut canvas = DataShaderCanvas::new(10, 10);
        canvas.set_bounds(BoundingBox::new(0.0, 1.0, 0.0, 1.0));

        // Add points to the canvas
        let points = vec![
            Point2f::new(0.1, 0.1),
            Point2f::new(0.12, 0.12),
            Point2f::new(0.08, 0.08),
        ];

        canvas.aggregate_points(&points);

        // Check that points were aggregated
        assert!(canvas.max_count() > 0);
    }

    #[test]
    fn test_should_activate() {
        assert!(!DataShader::should_activate(1000));
        assert!(!DataShader::should_activate(50000));
        assert!(DataShader::should_activate(100000));
        assert!(DataShader::should_activate(150000));
        assert!(DataShader::should_activate(1000000));
    }

    #[test]
    fn test_bounds_calculation() {
        let points = vec![(1.0, 2.0), (5.0, 8.0), (3.0, 4.0)];

        let bounds = DataShaderCanvas::calculate_bounds(&points).unwrap();

        assert_eq!(bounds.min_x, 1.0);
        assert_eq!(bounds.max_x, 5.0);
        assert_eq!(bounds.min_y, 2.0);
        assert_eq!(bounds.max_y, 8.0);
    }

    #[test]
    fn test_statistics() {
        let mut canvas = DataShaderCanvas::new(10, 10);
        canvas.set_bounds(BoundingBox::new(0.0, 1.0, 0.0, 1.0));

        // Add some test points
        let points = vec![Point2f::new(0.1, 0.1), Point2f::new(0.9, 0.9)];

        canvas.aggregate_points(&points);
        let stats = canvas.statistics();

        assert_eq!(stats.total_points, 2);
        assert!(stats.filled_pixels > 0);
        assert_eq!(stats.total_pixels, 100);
        assert!(stats.canvas_utilization > 0.0);
    }

    #[test]
    fn test_datashader_aggregate() {
        let mut ds = DataShader::with_canvas_size(100, 100);
        let x_data = vec![0.1, 0.2, 0.3, 0.4, 0.5];
        let y_data = vec![0.1, 0.2, 0.3, 0.4, 0.5];

        let result = ds.aggregate(&x_data, &y_data);
        assert!(result.is_ok());

        let stats = ds.statistics();
        assert_eq!(stats.total_points, 5);
    }

    #[test]
    fn test_datashader_render() {
        let mut ds = DataShader::with_canvas_size(10, 10);
        let x_data = vec![0.5];
        let y_data = vec![0.5];

        ds.aggregate(&x_data, &y_data).unwrap();
        let image = ds.render();

        assert_eq!(image.width, 10);
        assert_eq!(image.height, 10);
        assert_eq!(image.pixels.len(), 10 * 10 * 4); // RGBA
    }

    #[test]
    fn test_datashader_aggregate_with_explicit_bounds_uses_named_order() {
        let mut ds = DataShader::with_canvas_size(16, 16);
        let x_data = vec![0.25, 0.75];
        let y_data = vec![10.5, 19.5];

        ds.aggregate_with_bounds(&x_data, &y_data, 0.0, 1.0, 10.0, 20.0)
            .unwrap();

        let bounds = ds.canvas.bounds();
        assert_eq!(bounds.min_x, 0.0);
        assert_eq!(bounds.max_x, 1.0);
        assert_eq!(bounds.min_y, 10.0);
        assert_eq!(bounds.max_y, 20.0);
    }

    #[test]
    fn test_datashader_aggregate_with_explicit_bounds_rejects_invalid_range() {
        let mut ds = DataShader::with_canvas_size(16, 16);
        let x_data = vec![0.25, 0.75];
        let y_data = vec![10.5, 19.5];

        let err = ds
            .aggregate_with_bounds(&x_data, &y_data, 1.0, 0.0, 10.0, 20.0)
            .unwrap_err();

        match err {
            PlottingError::InvalidInput(message) => {
                assert!(message.contains("x_min < x_max"));
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    #[test]
    fn test_datashader_aggregate_with_explicit_bounds_rejects_non_finite_values() {
        let mut ds = DataShader::with_canvas_size(16, 16);
        let x_data = vec![0.25, 0.75];
        let y_data = vec![10.5, 19.5];

        let err = ds
            .aggregate_with_bounds(&x_data, &y_data, f64::NAN, 1.0, 10.0, 20.0)
            .unwrap_err();

        match err {
            PlottingError::InvalidInput(message) => {
                assert!(message.contains("must be finite"));
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }
}