runmat-plot 0.0.17

GPU-accelerated and static plotting for RunMat with WGPU and Plotters
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
//! Comprehensive integration tests for RunMat Plot
//!
//! Tests the complete plotting system including 2D plots, 3D plots,
//! Jupyter integration, and performance characteristics.

use runmat_plot::jupyter::{JupyterBackend, OutputFormat};
use runmat_plot::plots::*;

#[test]
fn test_complete_2d_plotting_pipeline() {
    // Test data
    let x_data = (0..100).map(|i| i as f64 * 0.1).collect::<Vec<_>>();
    let y_data = x_data.iter().map(|&x| x.sin()).collect::<Vec<_>>();

    // Create line plot
    let line_plot = LinePlot::new(x_data.clone(), y_data.clone())
        .unwrap()
        .with_label("sin(x)")
        .with_style(glam::Vec4::new(1.0, 0.0, 0.0, 1.0), 2.0, LineStyle::Solid);

    // Create scatter plot
    let scatter_data: Vec<f64> = (0..20).map(|i| (i as f64 * 0.5).cos()).collect();
    let scatter_x: Vec<f64> = (0..20).map(|i| i as f64 * 0.5).collect();

    let scatter_plot = ScatterPlot::new(scatter_x, scatter_data)
        .unwrap()
        .with_label("cos(x)")
        .with_style(
            glam::Vec4::new(0.0, 1.0, 0.0, 1.0),
            5.0,
            MarkerStyle::Circle,
        );

    // Create figure and combine plots
    let mut figure = Figure::new()
        .with_title("2D Multi-Plot Example")
        .with_labels("X", "Y")
        .with_grid(true);

    figure.add_line_plot(line_plot);
    figure.add_scatter_plot(scatter_plot);

    // Verify figure properties
    assert_eq!(figure.len(), 2);
    assert!(figure.title.is_some());
    assert!(figure.grid_enabled);
    assert!(figure.legend_enabled);

    // Test statistics
    let stats = figure.statistics();
    assert_eq!(stats.total_plots, 2);
    assert_eq!(stats.visible_plots, 2);
    assert!(stats.total_memory_usage > 0);

    // Test legend entries
    let legend_entries = figure.legend_entries();
    assert_eq!(legend_entries.len(), 2);
    assert_eq!(legend_entries[0].label, "sin(x)");
    assert_eq!(legend_entries[1].label, "cos(x)");
}

#[test]
fn test_3d_surface_plotting() {
    // Create test surface data
    let x_range = (-2.0, 2.0);
    let y_range = (-2.0, 2.0);
    let resolution = (20, 20);

    // Create surface from function: z = x^2 - y^2 (saddle point)
    let surface = SurfacePlot::from_function(x_range, y_range, resolution, |x, y| x * x - y * y)
        .unwrap()
        .with_colormap(ColorMap::Viridis)
        .with_shading(ShadingMode::Smooth)
        .with_alpha(0.8)
        .with_label("Saddle Surface");

    // Verify surface properties
    assert_eq!(surface.x_data.len(), 20);
    assert_eq!(surface.y_data.len(), 20);
    assert_eq!(surface.z_data.len(), 20);
    assert_eq!(surface.colormap, ColorMap::Viridis);
    assert_eq!(surface.shading_mode, ShadingMode::Smooth);
    assert_eq!(surface.alpha, 0.8);
    assert_eq!(surface.label, Some("Saddle Surface".to_string()));

    // Test statistics
    let stats = surface.statistics();
    assert_eq!(stats.grid_points, 400); // 20 * 20
    assert_eq!(stats.triangle_count, 722); // (20-1) * (20-1) * 2 = 722
    assert_eq!(stats.x_resolution, 20);
    assert_eq!(stats.y_resolution, 20);
    assert!(stats.memory_usage > 0);

    // Test bounds calculation
    let mut surface_mut = surface;
    let bounds = surface_mut.bounds();
    assert_eq!(bounds.min.x, -2.0);
    assert_eq!(bounds.max.x, 2.0);
    assert_eq!(bounds.min.y, -2.0);
    assert_eq!(bounds.max.y, 2.0);
    // Z bounds should be around [-4, 4] for x^2 - y^2 on [-2,2]x[-2,2]
    assert!(bounds.min.z >= -5.0 && bounds.min.z <= -3.0);
    assert!(bounds.max.z >= 3.0 && bounds.max.z <= 5.0);
}

#[test]
fn test_3d_point_cloud_visualization() {
    // Create test point cloud data (spiral)
    let num_points = 100;
    let positions: Vec<glam::Vec3> = (0..num_points)
        .map(|i| {
            let t = i as f32 * 0.3;
            let radius = 1.0 + t * 0.1;
            glam::Vec3::new(radius * t.cos(), radius * t.sin(), t * 0.5)
        })
        .collect();

    // Create values for color mapping
    let values: Vec<f64> = (0..num_points)
        .map(|i| (i as f64 / num_points as f64) * 10.0)
        .collect();

    // Create point cloud
    let point_cloud = PointCloudPlot::new(positions.clone())
        .with_values(values.clone())
        .unwrap()
        .with_colormap(ColorMap::Plasma)
        .with_point_style(PointStyle::Sphere)
        .with_size_mode(SizeMode::Proportional)
        .with_default_size(5.0)
        .with_label("Spiral Point Cloud");

    // Verify properties
    assert_eq!(point_cloud.len(), 100);
    assert_eq!(point_cloud.values, Some(values));
    assert_eq!(point_cloud.colormap, ColorMap::Plasma);
    assert_eq!(point_cloud.point_style, PointStyle::Sphere);
    assert_eq!(point_cloud.size_mode, SizeMode::Proportional);
    assert_eq!(point_cloud.default_size, 5.0);
    assert_eq!(point_cloud.label, Some("Spiral Point Cloud".to_string()));

    // Test statistics
    let stats = point_cloud.statistics();
    assert_eq!(stats.point_count, 100);
    assert!(stats.has_values);
    assert!(!stats.has_colors);
    assert!(!stats.has_sizes);
    assert!(stats.memory_usage > 0);

    // Test vertex generation
    let mut point_cloud_mut = point_cloud;
    let vertices = point_cloud_mut.generate_vertices();
    assert_eq!(vertices.len(), 100);

    // Verify first vertex
    assert_eq!(vertices[0].position, positions[0].to_array());

    // Test bounds
    let bounds = point_cloud_mut.bounds();
    assert!(bounds.max.x > bounds.min.x);
    assert!(bounds.max.y > bounds.min.y);
    assert!(bounds.max.z > bounds.min.z);
}

#[test]
fn test_colormap_functionality() {
    let colormaps = vec![
        ColorMap::Jet,
        ColorMap::Hot,
        ColorMap::Cool,
        ColorMap::Viridis,
        ColorMap::Plasma,
        ColorMap::Gray,
    ];

    for colormap in colormaps {
        // Test value mapping at different points
        let color_0 = colormap.map_value(0.0);
        let _color_half = colormap.map_value(0.5);
        let color_1 = colormap.map_value(1.0);

        // Verify colors are valid (0-1 range)
        assert!(color_0.x >= 0.0 && color_0.x <= 1.0);
        assert!(color_0.y >= 0.0 && color_0.y <= 1.0);
        assert!(color_0.z >= 0.0 && color_0.z <= 1.0);

        assert!(color_1.x >= 0.0 && color_1.x <= 1.0);
        assert!(color_1.y >= 0.0 && color_1.y <= 1.0);
        assert!(color_1.z >= 0.0 && color_1.z <= 1.0);

        // Verify different values give different colors (for most colormaps)
        if colormap != ColorMap::Gray {
            assert_ne!(color_0, color_1);
        }
    }

    // Test custom colormap
    let custom = ColorMap::Custom(
        glam::Vec4::new(1.0, 0.0, 0.0, 1.0), // Red
        glam::Vec4::new(0.0, 1.0, 0.0, 1.0), // Green
    );

    let custom_0 = custom.map_value(0.0);
    let custom_1 = custom.map_value(1.0);

    // Should interpolate from red to green
    assert!(custom_0.x > custom_0.y); // More red at 0
    assert!(custom_1.y > custom_1.x); // More green at 1
}

#[test]
fn test_matlab_compatibility_functions() {
    use runmat_plot::plots::point_cloud::matlab_compat as pc_compat;
    use runmat_plot::plots::surface::matlab_compat as surf_compat;

    // Test MATLAB-style surface plot
    let surf_x = vec![0.0, 1.0];
    let surf_y = vec![0.0, 1.0];
    let surf_z = vec![vec![0.0, 1.0], vec![1.0, 2.0]];

    let surface = surf_compat::surf(surf_x.clone(), surf_y.clone(), surf_z.clone()).unwrap();
    assert!(!surface.wireframe);

    let mesh = surf_compat::mesh(surf_x, surf_y, surf_z).unwrap();
    assert!(mesh.wireframe);

    // Test MATLAB-style 3D scatter
    let x3d = vec![0.0, 1.0, 2.0];
    let y3d = vec![0.0, 1.0, 2.0];
    let z3d = vec![0.0, 1.0, 2.0];

    let scatter3d = pc_compat::scatter3(x3d, y3d, z3d).unwrap();
    assert_eq!(scatter3d.len(), 3);
}

#[test]
fn test_jupyter_integration() {
    // Test Jupyter backend creation
    let backend = JupyterBackend::new();
    assert_eq!(backend.output_format, OutputFormat::HTML);

    // Test different output formats
    let formats = vec![
        OutputFormat::PNG,
        OutputFormat::SVG,
        OutputFormat::HTML,
        OutputFormat::Base64,
        OutputFormat::PlotlyJSON,
    ];

    for format in formats {
        let backend_fmt = JupyterBackend::with_format(format);
        assert_eq!(backend_fmt.output_format, format);
    }

    // Test direct backend usage
    let line_plot = LinePlot::new(vec![0.0, 1.0], vec![0.0, 1.0]).unwrap();
    let mut backend = JupyterBackend::new();

    // These should not panic and return valid output
    let display_result = backend.display_line_plot(&line_plot);
    assert!(display_result.is_ok());
}

#[test]
fn test_performance_characteristics() {
    use std::time::Instant;

    // Test large dataset handling
    let large_size = 10_000;
    let x_data: Vec<f64> = (0..large_size).map(|i| i as f64 * 0.001).collect();
    let y_data: Vec<f64> = x_data
        .iter()
        .map(|&x| x.sin() + 0.1 * (10.0 * x).sin())
        .collect();

    let start = Instant::now();
    let large_line_plot = LinePlot::new(x_data, y_data).unwrap();
    let creation_time = start.elapsed();

    // Creation should be reasonably fast
    assert!(creation_time.as_millis() < 100);

    // Memory usage should be reasonable
    let memory_usage = large_line_plot.estimated_memory_usage();
    let expected_min = large_size * 16; // 2 * f64 per point
    assert!(memory_usage >= expected_min);

    // Test statistics generation performance
    let start = Instant::now();
    let stats = large_line_plot.statistics();
    let stats_time = start.elapsed();

    assert!(stats_time.as_millis() < 10);
    assert_eq!(stats.point_count, large_size);

    // Test large surface plot
    let surface_start = Instant::now();
    let large_surface = SurfacePlot::from_function((-5.0, 5.0), (-5.0, 5.0), (100, 100), |x, y| {
        (x * x + y * y).sin()
    })
    .unwrap();
    let surface_creation_time = surface_start.elapsed();

    // Surface creation should complete in reasonable time
    assert!(surface_creation_time.as_millis() < 1000);

    let surface_stats = large_surface.statistics();
    assert_eq!(surface_stats.grid_points, 10_000); // 100 * 100
    assert_eq!(surface_stats.triangle_count, 19_602); // (100-1) * (100-1) * 2
}

#[test]
fn test_error_handling() {
    // Test invalid data dimensions
    let x = vec![0.0, 1.0, 2.0];
    let y = vec![0.0, 1.0]; // Mismatched length

    assert!(LinePlot::new(x.clone(), y.clone()).is_err());
    assert!(ScatterPlot::new(x, y).is_err());

    // Test empty data
    let empty_x: Vec<f64> = vec![];
    let empty_y: Vec<f64> = vec![];

    assert!(LinePlot::new(empty_x.clone(), empty_y.clone()).is_err());
    assert!(ScatterPlot::new(empty_x, empty_y).is_err());

    // Test invalid surface data
    let surf_x = vec![0.0, 1.0];
    let surf_y = vec![0.0, 1.0, 2.0];
    let surf_z = vec![vec![0.0, 1.0], vec![1.0, 2.0]]; // Wrong dimensions

    assert!(SurfacePlot::new(surf_x, surf_y, surf_z).is_err());

    // Test invalid point cloud operations
    let positions = vec![glam::Vec3::new(0.0, 0.0, 0.0)];
    let wrong_values = vec![1.0, 2.0]; // Length mismatch

    let point_cloud_result = PointCloudPlot::new(positions).with_values(wrong_values);
    assert!(point_cloud_result.is_err());
}

#[test]
fn test_memory_efficiency() {
    // Test that plots don't duplicate data unnecessarily
    let data_size = 1000;
    let x_data: Vec<f64> = (0..data_size).map(|i| i as f64).collect();
    let y_data: Vec<f64> = x_data.iter().map(|&x| x * 2.0).collect();

    let line_plot = LinePlot::new(x_data.clone(), y_data.clone()).unwrap();
    let initial_memory = line_plot.estimated_memory_usage();

    // Create multiple plots from same data
    let scatter_plot = ScatterPlot::new(x_data.clone(), y_data.clone()).unwrap();

    // Each plot should have similar memory usage (not sharing data currently, but reasonable)
    let scatter_memory = scatter_plot.estimated_memory_usage();
    let memory_ratio = scatter_memory as f64 / initial_memory as f64;

    // Memory usage should be in similar range (within 50% of each other)
    assert!(memory_ratio > 0.5 && memory_ratio < 2.0);

    // Test that cached data is reused
    let mut line_plot_mut = line_plot;
    let _vertices1 = line_plot_mut.generate_vertices();
    let memory_after_cache = line_plot_mut.estimated_memory_usage();

    // Memory should increase due to cached vertices
    assert!(memory_after_cache > initial_memory);

    // Generating vertices again should not increase memory further
    let _vertices2 = line_plot_mut.generate_vertices();
    let memory_after_reuse = line_plot_mut.estimated_memory_usage();

    assert_eq!(memory_after_cache, memory_after_reuse);
}

#[test]
fn test_plot_styling_and_customization() {
    // Test comprehensive styling options
    let x = vec![0.0, 1.0, 2.0];
    let y = vec![0.0, 1.0, 0.0];

    let styled_line = LinePlot::new(x.clone(), y.clone())
        .unwrap()
        .with_style(glam::Vec4::new(0.8, 0.2, 0.1, 0.9), 3.5, LineStyle::Dashed)
        .with_label("Styled Line");

    assert_eq!(styled_line.color, glam::Vec4::new(0.8, 0.2, 0.1, 0.9));
    assert_eq!(styled_line.line_width, 3.5);
    assert_eq!(styled_line.line_style, LineStyle::Dashed);
    assert_eq!(styled_line.label, Some("Styled Line".to_string()));

    // Test surface styling
    let surface = SurfacePlot::new(
        vec![0.0, 1.0],
        vec![0.0, 1.0],
        vec![vec![0.0, 1.0], vec![1.0, 2.0]],
    )
    .unwrap()
    .with_colormap(ColorMap::Hot)
    .with_shading(ShadingMode::Faceted)
    .with_wireframe(true)
    .with_alpha(0.7);

    assert_eq!(surface.colormap, ColorMap::Hot);
    assert_eq!(surface.shading_mode, ShadingMode::Faceted);
    assert!(surface.wireframe);
    assert_eq!(surface.alpha, 0.7);
}

#[test]
fn test_bounds_calculation_accuracy() {
    // Test with known data
    let x = vec![-3.0, -1.0, 0.0, 2.0, 4.0];
    let y = vec![-2.0, 0.0, 1.0, -1.0, 3.0];

    let mut line_plot = LinePlot::new(x, y).unwrap();
    let bounds = line_plot.bounds();

    assert_eq!(bounds.min.x, -3.0);
    assert_eq!(bounds.max.x, 4.0);
    assert_eq!(bounds.min.y, -2.0);
    assert_eq!(bounds.max.y, 3.0);
    assert_eq!(bounds.min.z, 0.0); // 2D plot
    assert_eq!(bounds.max.z, 0.0); // 2D plot

    // Test surface bounds with known function
    let mut surface = SurfacePlot::from_function(
        (-1.0, 1.0),
        (-1.0, 1.0),
        (3, 3),
        |x, y| x + y, // Simple linear function
    )
    .unwrap();

    let surface_bounds = surface.bounds();
    assert_eq!(surface_bounds.min.x, -1.0);
    assert_eq!(surface_bounds.max.x, 1.0);
    assert_eq!(surface_bounds.min.y, -1.0);
    assert_eq!(surface_bounds.max.y, 1.0);
    assert_eq!(surface_bounds.min.z, -2.0); // min(x+y) = -1 + -1 = -2
    assert_eq!(surface_bounds.max.z, 2.0); // max(x+y) = 1 + 1 = 2
}