flow-plots 0.3.1

Package for drawing and interacting with plots in flow cytometry data
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
// Tests for flow-plots
//
// Tests for the new API using DensityPlotOptions, BasePlotOptions, and AxisOptions
// with the builder pattern.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::colormap::ColorMaps;
    use crate::helpers::density_options_from_fcs;
    use crate::options::{AxisOptions, BasePlotOptions, DensityPlotOptions, PlotOptions};
    use crate::histogram_data::HistogramData;
    use crate::options::HistogramPlotOptions;
    use crate::plots::density::DensityPlot;
    use crate::plots::histogram::HistogramPlot;
    use crate::render::RenderConfig;
    use flow_fcs::{Fcs, Parameter, TransformType};
    use polars::prelude::*;
    use std::fs::File;
    use std::io::Write;
    // Note: Some imports may not be needed but are kept for future use
    use std::sync::Arc;

    // Helper to create a test FCS struct
    fn create_test_fcs() -> anyhow::Result<Fcs> {
        // Create a temporary file for testing
        let temp_path = std::env::temp_dir().join("test_fcs_plots.tmp");
        {
            let mut f = File::create(&temp_path)?;
            f.write_all(b"test")?;
        }

        // Create test DataFrame with more data points for percentile testing
        let mut columns = Vec::new();
        columns.push(Column::new(
            "FSC-A".into(),
            (0..100).map(|i| i as f32 * 100.0).collect::<Vec<f32>>(),
        ));
        columns.push(Column::new(
            "SSC-A".into(),
            (0..100).map(|i| i as f32 * 50.0).collect::<Vec<f32>>(),
        ));
        columns.push(Column::new(
            "FL1-A".into(),
            (0..100).map(|i| i as f32 * 10.0).collect::<Vec<f32>>(),
        ));
        columns.push(Column::new(
            "Time".into(),
            (0..100).map(|i| i as f32).collect::<Vec<f32>>(),
        ));

        let df = DataFrame::new(columns).expect("Failed to create test DataFrame");

        // Create parameter map using internal types (similar to flow-fcs tests)
        use flow_fcs::parameter::ParameterMap;
        use flow_fcs::parameter::ParameterProcessing;
        let mut params = ParameterMap::default();
        params.insert(
            "FSC-A".into(),
            Parameter::new(&1, "FSC-A", "FSC-A", &TransformType::Linear),
        );
        params.insert(
            "SSC-A".into(),
            Parameter::new(&2, "SSC-A", "SSC-A", &TransformType::Linear),
        );
        params.insert(
            "FL1-A".into(),
            Parameter::new(
                &3,
                "FL1-A",
                "FL1-A",
                &TransformType::Arcsinh { cofactor: 200.0 },
            ),
        );
        params.insert(
            "Time".into(),
            Parameter::new(&4, "Time", "Time", &TransformType::Linear),
        );

        // Create metadata with $FIL keyword
        use flow_fcs::keyword::Keyword;
        use flow_fcs::metadata::Metadata;
        let mut metadata = Metadata::new();
        metadata.keywords.insert(
            "$FIL".to_string(),
            Keyword::String("test_file.fcs".to_string()),
        );

        Ok(Fcs {
            header: flow_fcs::Header::new(),
            metadata,
            parameters: params,
            data_frame: Arc::new(df),
            file_access: flow_fcs::file::AccessWrapper::new(temp_path.to_str().unwrap_or(""))?,
        })
    }

    // ============================================================================
    // BasePlotOptions Tests
    // ============================================================================

    #[test]
    fn test_base_plot_options_default() {
        let options = BasePlotOptions::default();
        assert_eq!(options.width, 400);
        assert_eq!(options.height, 400);
        assert_eq!(options.margin, 10);
        assert_eq!(options.x_label_area_size, 50);
        assert_eq!(options.y_label_area_size, 50);
        assert_eq!(options.title, "Density Plot");
    }

    #[test]
    fn test_base_plot_options_builder() {
        let options = BasePlotOptions::new()
            .width(800)
            .height(600)
            .margin(20)
            .x_label_area_size(60)
            .y_label_area_size(70)
            .title("Custom Plot".to_string())
            .build()
            .unwrap();

        assert_eq!(options.width, 800);
        assert_eq!(options.height, 600);
        assert_eq!(options.margin, 20);
        assert_eq!(options.x_label_area_size, 60);
        assert_eq!(options.y_label_area_size, 70);
        assert_eq!(options.title, "Custom Plot");
    }

    #[test]
    fn test_base_plot_options_builder_partial() {
        // Test that we can set only some fields
        let options = BasePlotOptions::new()
            .width(1000)
            .height(750)
            .build()
            .unwrap();

        assert_eq!(options.width, 1000);
        assert_eq!(options.height, 750);
        // Other fields should use defaults
        assert_eq!(options.margin, 10);
        assert_eq!(options.title, "Density Plot");
    }

    // ============================================================================
    // AxisOptions Tests
    // ============================================================================

    #[test]
    fn test_axis_options_default() {
        let options = AxisOptions::default();
        assert_eq!(*options.range.start(), 0.0);
        assert_eq!(*options.range.end(), 200_000.0);
        assert!(matches!(options.transform, TransformType::Arcsinh { .. }));
        assert_eq!(options.label, None);
    }

    #[test]
    fn test_axis_options_builder() {
        let options = AxisOptions::new()
            .range(0.0..=1000.0)
            .transform(TransformType::Linear)
            .label("X-Axis".to_string())
            .build()
            .unwrap();

        assert_eq!(*options.range.start(), 0.0);
        assert_eq!(*options.range.end(), 1000.0);
        assert_eq!(options.transform, TransformType::Linear);
        assert_eq!(options.label, Some("X-Axis".to_string()));
    }

    #[test]
    fn test_axis_options_arcsinh_transform() {
        let options = AxisOptions::new()
            .range(0.0..=5000.0)
            .transform(TransformType::Arcsinh { cofactor: 150.0 })
            .build()
            .unwrap();

        assert_eq!(
            options.transform,
            TransformType::Arcsinh { cofactor: 150.0 }
        );
    }

    // ============================================================================
    // DensityPlotOptions Tests
    // ============================================================================

    #[test]
    fn test_density_plot_options_default() {
        let options = DensityPlotOptions::default();
        assert_eq!(options.base.width, 400);
        assert_eq!(options.base.height, 400);
        assert_eq!(*options.x_axis.range.start(), 0.0);
        assert_eq!(*options.x_axis.range.end(), 200_000.0);
        assert!(matches!(options.colormap, ColorMaps::Viridis(_)));
    }

    #[test]
    fn test_density_plot_options_builder() {
        let base = BasePlotOptions::new()
            .width(800)
            .height(600)
            .title("Test Plot".to_string())
            .build()
            .unwrap();

        let x_axis = AxisOptions::new()
            .range(0.0..=10_000.0)
            .transform(TransformType::Linear)
            .label("FSC-A".to_string())
            .build()
            .unwrap();

        let y_axis = AxisOptions::new()
            .range(0.0..=5_000.0)
            .transform(TransformType::Arcsinh { cofactor: 150.0 })
            .label("SSC-A".to_string())
            .build()
            .unwrap();

        let options = DensityPlotOptions::new()
            .base(base)
            .x_axis(x_axis)
            .y_axis(y_axis)
            .build()
            .unwrap();

        assert_eq!(options.base.width, 800);
        assert_eq!(options.base.height, 600);
        assert_eq!(options.base.title, "Test Plot");
        assert_eq!(*options.x_axis.range.start(), 0.0);
        assert_eq!(*options.x_axis.range.end(), 10_000.0);
        assert_eq!(*options.y_axis.range.start(), 0.0);
        assert_eq!(*options.y_axis.range.end(), 5_000.0);
        assert_eq!(options.x_axis.label, Some("FSC-A".to_string()));
        assert_eq!(options.y_axis.label, Some("SSC-A".to_string()));
    }

    #[test]
    fn test_density_plot_options_plot_options_trait() {
        let options = DensityPlotOptions::default();
        let base = options.base();
        assert_eq!(base.width, 400);
        assert_eq!(base.height, 400);
    }

    // ============================================================================
    // Helper Function Tests
    // ============================================================================
    // Note: These tests require the Transformable trait to be exported from flow-fcs.
    // They will compile once that export is available.

    #[test]
    fn test_density_options_from_fcs_fsc_ssc() {
        let fcs = create_test_fcs().unwrap();
        let x_param = fcs.find_parameter("FSC-A").unwrap();
        let y_param = fcs.find_parameter("SSC-A").unwrap();

        let builder = density_options_from_fcs(&fcs, x_param, y_param).unwrap();
        let options = builder.build().unwrap();

        // FSC/SSC should use default range
        assert_eq!(*options.x_axis.range.start(), 0.0);
        assert_eq!(*options.x_axis.range.end(), 200_000.0);
        assert_eq!(*options.y_axis.range.start(), 0.0);
        assert_eq!(*options.y_axis.range.end(), 200_000.0);

        // FSC/SSC should use Linear transform
        assert_eq!(options.x_axis.transform, TransformType::Linear);
        assert_eq!(options.y_axis.transform, TransformType::Linear);

        // Title should be extracted from $FIL keyword
        assert_eq!(options.base.title, "test_file.fcs");
    }

    #[test]
    fn test_density_options_from_fcs_fluorescence() {
        let fcs = create_test_fcs().unwrap();
        let x_param = fcs.find_parameter("FL1-A").unwrap();
        let y_param = fcs.find_parameter("FL1-A").unwrap();

        let builder = density_options_from_fcs(&fcs, x_param, y_param).unwrap();
        let options = builder.build().unwrap();

        // Fluorescence should calculate percentile bounds
        // Data ranges from 0 to 990 (100 points * 10.0)
        // After arcsinh transform, percentiles should be calculated
        assert!(*options.x_axis.range.start() >= 0.0);
        assert!(*options.x_axis.range.end() <= 1000.0);

        // Should use arcsinh transform (from parameter)
        assert!(matches!(
            options.x_axis.transform,
            TransformType::Arcsinh { .. }
        ));
    }

    #[test]
    fn test_density_options_from_fcs_time() {
        let fcs = create_test_fcs().unwrap();
        let x_param = fcs.find_parameter("Time").unwrap();
        let y_param = fcs.find_parameter("Time").unwrap();

        let builder = density_options_from_fcs(&fcs, x_param, y_param).unwrap();
        let options = builder.build().unwrap();

        // Time should use actual max value
        // Data ranges from 0 to 99
        assert!(*options.x_axis.range.start() == 0.0);
        assert!(*options.x_axis.range.end() >= 99.0);
    }

    #[test]
    fn test_density_options_from_fcs_customization() {
        let fcs = create_test_fcs().unwrap();
        let x_param = fcs.find_parameter("FSC-A").unwrap();
        let y_param = fcs.find_parameter("SSC-A").unwrap();

        let builder = density_options_from_fcs(&fcs, x_param, y_param).unwrap();
        let options = builder.width(1200).height(900).build().unwrap();

        // Custom dimensions should be applied
        assert_eq!(options.base.width, 1200);
        assert_eq!(options.base.height, 900);
    }

    // ============================================================================
    // Utility Function Tests
    // ============================================================================

    #[test]
    fn test_get_percentile_bounds() {
        let values = vec![10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0];
        let range = crate::get_percentile_bounds(&values, 0.1, 0.9);

        // 10th percentile should be around 10-20, 90th around 90-100
        assert!(*range.start() <= 20.0);
        assert!(*range.end() >= 90.0);
    }

    #[test]
    fn test_get_percentile_bounds_single_value() {
        let values = vec![42.0];
        let range = crate::get_percentile_bounds(&values, 0.01, 0.99);
        assert!(*range.start() <= 42.0);
        assert!(*range.end() >= 42.0);
    }

    #[test]
    fn test_get_percentile_bounds_empty() {
        let values = vec![];
        let range = crate::get_percentile_bounds(&values, 0.01, 0.99);
        // Should handle empty gracefully (will panic on index access, but that's expected)
        // In practice, this shouldn't happen, but we test the bounds checking
    }

    #[test]
    fn test_create_axis_specs_linear() {
        let range_x = 0.0..=1000.0;
        let range_y = 0.0..=500.0;
        let x_transform = TransformType::Linear;
        let y_transform = TransformType::Linear;

        let (x_spec, y_spec) =
            crate::create_axis_specs(&range_x, &range_y, &x_transform, &y_transform).unwrap();

        // Linear should use nice bounds
        assert!(x_spec.start <= 0.0);
        assert!(x_spec.end >= 1000.0);
        assert!(y_spec.start <= 0.0);
        assert!(y_spec.end >= 500.0);
    }

    #[test]
    fn test_create_axis_specs_arcsinh() {
        let range_x = 0.0..=1000.0;
        let range_y = 0.0..=500.0;
        let x_transform = TransformType::Arcsinh { cofactor: 200.0 };
        let y_transform = TransformType::Arcsinh { cofactor: 150.0 };

        let (x_spec, y_spec) =
            crate::create_axis_specs(&range_x, &range_y, &x_transform, &y_transform).unwrap();

        // Arcsinh should preserve the range
        assert_eq!(x_spec.start, 0.0);
        assert_eq!(x_spec.end, 1000.0);
        assert_eq!(y_spec.start, 0.0);
        assert_eq!(y_spec.end, 500.0);
    }

    // ============================================================================
    // Plot Rendering Tests
    // ============================================================================

    #[test]
    fn test_density_plot_render_empty_data() {
        let plot = DensityPlot::new();
        let options = DensityPlotOptions::default();
        let data: Vec<(f32, f32)> = vec![];
        let mut render_config = RenderConfig::default();

        // Should handle empty data gracefully
        let result = plot.render(data.into(), &options, &mut render_config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_density_plot_render_small_dataset() {
        let plot = DensityPlot::new();
        let options = DensityPlotOptions::new()
            .width(100)
            .height(100)
            .build()
            .unwrap();
        let data: Vec<(f32, f32)> = vec![(100.0, 200.0), (150.0, 250.0), (200.0, 300.0)];
        let mut render_config = RenderConfig::default();

        let result = plot.render(data.into(), &options, &mut render_config);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        // Should produce JPEG bytes
        assert!(!bytes.is_empty());
        // JPEG files start with FF D8 FF
        assert_eq!(bytes[0], 0xFF);
        assert_eq!(bytes[1], 0xD8);
    }

    // ============================================================================
    // Histogram Plot Tests
    // ============================================================================

    #[test]
    fn test_histogram_plot_render_raw_values() {
        let plot = HistogramPlot::new();
        let options = HistogramPlotOptions::new()
            .base(BasePlotOptions::new().width(200).height(200).build().unwrap())
            .x_axis(
                AxisOptions::new()
                    .range(0.0..=100.0)
                    .build()
                    .unwrap(),
            )
            .histogram_filled(true)
            .num_bins(20usize)
            .build()
            .unwrap();
        let data = HistogramData::from_values(vec![
            10.0, 15.0, 20.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0,
        ]);
        let mut render_config = RenderConfig::default();

        let result = plot.render(data, &options, &mut render_config);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
        assert_eq!(bytes[0], 0xFF);
        assert_eq!(bytes[1], 0xD8);
    }

    #[test]
    fn test_histogram_plot_render_unfilled() {
        let plot = HistogramPlot::new();
        let options = HistogramPlotOptions::new()
            .base(BasePlotOptions::new().width(200).height(200).build().unwrap())
            .x_axis(
                AxisOptions::new()
                    .range(0.0..=50.0)
                    .build()
                    .unwrap(),
            )
            .histogram_filled(false)
            .num_bins(10usize)
            .build()
            .unwrap();
        let data = HistogramData::from_values(vec![5.0, 10.0, 10.0, 15.0, 20.0]);
        let mut render_config = RenderConfig::default();

        let result = plot.render(data, &options, &mut render_config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_histogram_plot_render_pre_binned() {
        let plot = HistogramPlot::new();
        let options = HistogramPlotOptions::new()
            .base(BasePlotOptions::new().width(200).height(200).build().unwrap())
            .build()
            .unwrap();
        let data = HistogramData::pre_binned(
            vec![0.0, 1.0, 2.0, 3.0, 4.0],
            vec![5.0, 10.0, 7.0, 3.0],
        )
        .unwrap();
        let mut render_config = RenderConfig::default();

        let result = plot.render(data, &options, &mut render_config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_histogram_plot_render_overlaid() {
        let plot = HistogramPlot::new();
        let options = HistogramPlotOptions::new()
            .base(BasePlotOptions::new().width(200).height(200).build().unwrap())
            .x_axis(
                AxisOptions::new()
                    .range(0.0..=100.0)
                    .build()
                    .unwrap(),
            )
            .histogram_filled(true)
            .scale_to_peak(true)
            .baseline_separation(0.2)
            .num_bins(15usize)
            .build()
            .unwrap();
        let data = HistogramData::overlaid(vec![
            (vec![10.0, 20.0, 20.0, 30.0], 0),
            (vec![25.0, 35.0, 35.0, 45.0], 1),
        ]);
        let mut render_config = RenderConfig::default();

        let result = plot.render(data, &options, &mut render_config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_histogram_plot_render_empty() {
        let plot = HistogramPlot::new();
        let options = HistogramPlotOptions::new()
            .base(BasePlotOptions::new().width(100).height(100).build().unwrap())
            .build()
            .unwrap();
        let data = HistogramData::from_values(vec![]);
        let mut render_config = RenderConfig::default();

        let result = plot.render(data, &options, &mut render_config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_density_plot_render_with_progress_callback() {
        let plot = DensityPlot::new();
        let options = DensityPlotOptions::new()
            .width(200)
            .height(200)
            .build()
            .unwrap();

        // Create data that will trigger progress updates
        let data: Vec<(f32, f32)> = (0..1000)
            .map(|i| (i as f32 * 10.0, i as f32 * 5.0))
            .collect();

        let mut progress_calls = 0;
        let mut render_config = RenderConfig {
            progress: Some(Box::new(move |_info| {
                progress_calls += 1;
                Ok(())
            })),
            ..Default::default()
        };

        let result = plot.render(data.into(), &options, &mut render_config);
        assert!(result.is_ok());
        // Progress should have been called at least once
        assert!(progress_calls > 0);
    }

    // ============================================================================
    // Transform Tests
    // ============================================================================

    #[test]
    fn test_transform_application_in_helper() {
        let fcs = create_test_fcs().unwrap();
        let x_param = fcs.find_parameter("FL1-A").unwrap();

        // Verify that the parameter has arcsinh transform
        assert!(matches!(x_param.transform, TransformType::Arcsinh { .. }));

        // Get raw data
        let raw_data = fcs.get_parameter_events_slice("FL1-A").unwrap();
        assert!(!raw_data.is_empty());

        // Transform should be applied in helper function
        let transformed: Vec<f32> = raw_data
            .iter()
            .map(|&v| x_param.transform.transform(&v))
            .collect();

        // Transformed values should be different from raw (for non-zero values)
        if raw_data[0] != 0.0 {
            assert_ne!(transformed[0], raw_data[0]);
        }
    }

    // ============================================================================
    // Edge Cases and Error Handling
    // ============================================================================

    #[test]
    fn test_builder_with_invalid_range() {
        // Builder should accept any valid range
        let options = AxisOptions::new()
            .range(100.0..=50.0) // Invalid: start > end
            .build();

        // Builder doesn't validate ranges, so this should succeed
        // (validation would happen at render time)
        assert!(options.is_ok());
    }

    #[test]
    fn test_density_plot_options_builder_chaining() {
        // Test that we can chain builder methods
        let options = DensityPlotOptions::new()
            .width(800)
            .height(600)
            .build()
            .unwrap();

        assert_eq!(options.base.width, 800);
        assert_eq!(options.base.height, 600);
    }

    #[test]
    fn test_render_config_default() {
        let config = RenderConfig::default();
        assert!(config.progress.is_none());
    }

    #[test]
    fn test_density_plot_new() {
        let plot = DensityPlot::new();
        // Should create successfully
        assert!(std::mem::size_of_val(&plot) == 0); // Unit struct
    }

    // ============================================================================
    // Batch API Tests
    // ============================================================================

    #[test]
    fn test_calculate_density_per_pixel_batch_empty() {
        use crate::density_calc::calculate_density_per_pixel_batch;
        use crate::ScatterPlotData;

        let requests: Vec<(ScatterPlotData, DensityPlotOptions)> = vec![];
        let results = calculate_density_per_pixel_batch(&requests);
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_calculate_density_per_pixel_batch_single_plot() {
        use crate::density_calc::{calculate_density_per_pixel, calculate_density_per_pixel_batch};
        use crate::ScatterPlotData;

        let options = DensityPlotOptions::new()
            .width(100)
            .height(100)
            .build()
            .unwrap();
        let data = vec![(100.0, 200.0), (150.0, 250.0), (200.0, 300.0)];

        // Single plot via batch
        let batch_results = calculate_density_per_pixel_batch(&[(data.clone().into(), options.clone())]);
        assert_eq!(batch_results.len(), 1);

        // Single plot via direct call
        let direct_result = calculate_density_per_pixel(&data, 100, 100, &options);

        // Results should be similar (same number of pixels, similar positions)
        assert_eq!(batch_results[0].len(), direct_result.len());
    }

    #[test]
    fn test_calculate_density_per_pixel_batch_multiple_plots() {
        use crate::density_calc::calculate_density_per_pixel_batch;
        use crate::ScatterPlotData;

        let options1 = DensityPlotOptions::new()
            .width(100)
            .height(100)
            .build()
            .unwrap();
        let options2 = DensityPlotOptions::new()
            .width(200)
            .height(200)
            .build()
            .unwrap();

        let data1 = vec![(100.0, 200.0), (150.0, 250.0)];
        let data2 = vec![(50.0, 100.0), (75.0, 125.0), (100.0, 150.0)];

        let requests = vec![
            (data1.into(), options1),
            (data2.into(), options2),
        ];

        let results = calculate_density_per_pixel_batch(&requests);
        assert_eq!(results.len(), 2);
        assert!(!results[0].is_empty());
        assert!(!results[1].is_empty());
    }

    #[test]
    fn test_calculate_density_per_pixel_batch_different_sizes() {
        use crate::density_calc::calculate_density_per_pixel_batch;
        use crate::ScatterPlotData;

        let requests: Vec<(ScatterPlotData, DensityPlotOptions)> = vec![
            (
                vec![(100.0, 200.0)].into(),
                DensityPlotOptions::new().width(800).height(600).build().unwrap(),
            ),
            (
                vec![(50.0, 100.0)].into(),
                DensityPlotOptions::new().width(1024).height(768).build().unwrap(),
            ),
            (
                vec![(200.0, 300.0)].into(),
                DensityPlotOptions::new().width(640).height(480).build().unwrap(),
            ),
        ];

        let results = calculate_density_per_pixel_batch(&requests);
        assert_eq!(results.len(), 3);
        // Each result should have pixels
        for result in &results {
            assert!(!result.is_empty());
        }
    }

    #[test]
    fn test_render_batch_empty() {
        use crate::ScatterPlotData;

        let plot = DensityPlot::new();
        let requests: Vec<(ScatterPlotData, DensityPlotOptions)> = vec![];
        let mut render_config = RenderConfig::default();

        let results = plot.render_batch(&requests, &mut render_config).unwrap();
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_render_batch_single_plot() {
        use crate::ScatterPlotData;

        let plot = DensityPlot::new();
        let options = DensityPlotOptions::new()
            .width(100)
            .height(100)
            .build()
            .unwrap();
        let data = vec![(100.0, 200.0), (150.0, 250.0)];
        let requests = vec![(data.into(), options)];
        let mut render_config = RenderConfig::default();

        let results = plot.render_batch(&requests, &mut render_config).unwrap();
        assert_eq!(results.len(), 1);
        assert!(!results[0].is_empty());
        // Should be JPEG bytes
        assert_eq!(results[0][0], 0xFF);
        assert_eq!(results[0][1], 0xD8);
    }

    #[test]
    fn test_render_batch_multiple_plots() {
        use crate::ScatterPlotData;

        let plot = DensityPlot::new();
        let options1 = DensityPlotOptions::new()
            .width(100)
            .height(100)
            .build()
            .unwrap();
        let options2 = DensityPlotOptions::new()
            .width(200)
            .height(200)
            .build()
            .unwrap();

        let data1 = vec![(100.0, 200.0), (150.0, 250.0)];
        let data2 = vec![(50.0, 100.0), (75.0, 125.0), (100.0, 150.0)];

        let requests = vec![
            (data1.into(), options1),
            (data2.into(), options2),
        ];
        let mut render_config = RenderConfig::default();

        let results = plot.render_batch(&requests, &mut render_config).unwrap();
        assert_eq!(results.len(), 2);
        for result in &results {
            assert!(!result.is_empty());
            // Should be JPEG bytes
            assert_eq!(result[0], 0xFF);
            assert_eq!(result[1], 0xD8);
        }
    }
}