ruviz 0.6.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
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! KDE (Kernel Density Estimation) plot implementations
//!
//! Provides smooth distribution visualization through kernel density estimation.
//!
//! # Trait-Based API
//!
//! The KDE plot implements the plot traits for unified behavior:
//! - [`crate::plots::PlotCompute`]: Transforms input data into KDE curves
//! - [`crate::plots::PlotData`]: Provides data bounds and emptiness check
//! - [`crate::plots::PlotRender`]: Renders to a canvas
//!
//! # Example
//!
//! ```rust,ignore
//! use ruviz::prelude::*;
//!
//! // Zero-ceremony API (recommended)
//! Plot::new()
//!     .kde(&data)
//!     .bandwidth(0.5)
//!     .fill(true)
//!     .title("KDE Distribution")
//!     .save("kde.png")?;
//! ```

use crate::core::error::Result;
use crate::core::style_utils::StyleResolver;
use crate::plots::distribution::violin::BandwidthMethod;
use crate::plots::traits::{PlotArea, PlotCompute, PlotConfig, PlotData, PlotRender};
use crate::render::{Color, ColorMapSpec, LineStyle, SkiaRenderer, Theme};
use crate::stats::kde::{kde_1d, kde_2d};

// =============================================================================
// KDE Configuration
// =============================================================================

/// Configuration for KDE plot
///
/// Controls the appearance and computation of kernel density estimation plots.
///
/// # Example
///
/// ```rust
/// use ruviz::plots::distribution::KdeConfig;
///
/// let config = KdeConfig::new()
///     .bandwidth(0.5)
///     .n_points(200)
///     .fill(true)
///     .fill_alpha(0.3);
/// ```
#[allow(deprecated)] // the derives touch the deprecated `shade` field
#[derive(Debug, Clone)]
pub struct KdeConfig {
    /// Bandwidth selection method (defaults to Scott's rule)
    ///
    /// Spelled exactly as it is on [`ViolinConfig`](crate::plots::ViolinConfig),
    /// the other kernel-density plot type: a [`BandwidthMethod`], or a bare
    /// number for a fixed bandwidth.
    pub bandwidth: BandwidthMethod,
    /// Number of points for density curve
    pub n_points: usize,
    /// Fill under the curve
    pub fill: bool,
    /// Fill alpha
    pub fill_alpha: f32,
    /// Line color (None for auto)
    pub color: Option<Color>,
    /// Line width
    pub line_width: f32,
    /// Whether to shade based on density
    ///
    /// Not implemented. Filling the area under the curve is [`KdeConfig::fill`]
    /// plus [`KdeConfig::fill_alpha`]; density-proportional shading has no
    /// renderer behind it.
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. Use KdeConfig::fill / KdeConfig::fill_alpha to fill under the curve"
    )]
    pub shade: bool,
    /// Vertical reference lines drawn at these x values
    ///
    /// See [`KdeConfig::vertical_line`].
    pub vertical_lines: Vec<f64>,
    /// Cumulative distribution
    pub cumulative: bool,
    /// Whether to clip at data bounds
    pub clip: Option<(f64, f64)>,
}

impl Default for KdeConfig {
    #[allow(deprecated)] // `shade` still has to be populated while it exists
    fn default() -> Self {
        Self {
            bandwidth: BandwidthMethod::Scott,
            n_points: 200,
            fill: true,
            fill_alpha: 0.3,
            color: None,
            line_width: 2.0,
            shade: false,
            vertical_lines: vec![],
            cumulative: false,
            clip: None,
        }
    }
}

// Implement PlotConfig marker trait
impl PlotConfig for KdeConfig {}

impl KdeConfig {
    /// Create new config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the bandwidth selection method.
    ///
    /// Takes a [`BandwidthMethod`] or, via [`From<f64>`], a fixed bandwidth:
    /// `.bandwidth(0.5)` is `.bandwidth(BandwidthMethod::Fixed(0.5))`.
    pub fn bandwidth(mut self, bw: impl Into<BandwidthMethod>) -> Self {
        self.bandwidth = bw.into();
        self
    }

    /// Set number of points
    pub fn n_points(mut self, n: usize) -> Self {
        self.n_points = n.max(10);
        self
    }

    /// Enable/disable fill
    pub fn fill(mut self, fill: bool) -> Self {
        self.fill = fill;
        self
    }

    /// Set fill alpha
    pub fn fill_alpha(mut self, alpha: f32) -> Self {
        self.fill_alpha = alpha.clamp(0.0, 1.0);
        self
    }

    /// Set line color
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Set line width
    pub fn line_width(mut self, width: f32) -> Self {
        self.line_width = width.max(0.1);
        self
    }

    /// Enable cumulative distribution
    pub fn cumulative(mut self, cumulative: bool) -> Self {
        self.cumulative = cumulative;
        self
    }

    /// Set clip bounds
    pub fn clip(mut self, min: f64, max: f64) -> Self {
        self.clip = Some((min, max));
        self
    }

    /// Add a vertical reference line at `x`
    ///
    /// The line is drawn dashed, in the series colour, spanning the full height
    /// of the plot area. Call repeatedly to add several.
    pub fn vertical_line(mut self, x: f64) -> Self {
        self.vertical_lines.push(x);
        self
    }

    /// Replace the whole set of vertical reference lines
    pub fn vertical_lines(mut self, xs: impl IntoIterator<Item = f64>) -> Self {
        self.vertical_lines = xs.into_iter().collect();
        self
    }
}

/// Deprecated alias for backward compatibility
#[deprecated(since = "0.1.0", note = "Use KdeConfig instead")]
pub type KdePlotConfig = KdeConfig;

// =============================================================================
// KDE Data
// =============================================================================

/// Computed KDE data for plotting
///
/// Contains the density curve coordinates and metadata from KDE computation.
/// This struct implements [`PlotData`] and [`PlotRender`] traits.
///
/// # Example
///
/// ```rust
/// use ruviz::plots::distribution::{KdeConfig, compute_kde};
///
/// let data = vec![1.0, 2.0, 2.5, 3.0, 3.5, 4.0];
/// let kde_data = compute_kde(&data, &KdeConfig::default());
///
/// // Access computed values
/// println!("Bandwidth: {}", kde_data.bandwidth);
/// println!("Points: {}", kde_data.x.len());
/// ```
#[derive(Debug, Clone)]
pub struct KdeData {
    /// X coordinates
    pub x: Vec<f64>,
    /// Y coordinates (density or cumulative)
    pub y: Vec<f64>,
    /// Bandwidth used
    pub bandwidth: f64,
    /// Whether this is cumulative
    pub cumulative: bool,
    /// Configuration used for computation (for rendering)
    pub(crate) config: KdeConfig,
}

/// Deprecated alias for backward compatibility
#[deprecated(since = "0.1.0", note = "Use KdeData instead")]
pub type KdePlotData = KdeData;

/// Width, in points, of the reference lines drawn by
/// [`KdeConfig::vertical_line`].
const KDE_VERTICAL_LINE_WIDTH_PT: f32 = 1.0;

impl KdeData {
    /// Draw the configured vertical reference lines across the plot area.
    ///
    /// Backs [`KdeConfig::vertical_line`]. Lines outside the visible x range are
    /// skipped rather than clamped to the border, so an off-screen reference
    /// does not masquerade as an axis spine.
    fn draw_vertical_lines(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        color: Color,
    ) -> Result<()> {
        if self.config.vertical_lines.is_empty() {
            return Ok(());
        }

        let clip_rect = (area.x, area.y, area.width, area.height);
        let width = renderer
            .render_scale()
            .points_to_pixels(KDE_VERTICAL_LINE_WIDTH_PT);
        let top = area.y;
        let bottom = area.y + area.height;

        for &x in &self.config.vertical_lines {
            if !x.is_finite() {
                continue;
            }
            let (px, _) = area.data_to_screen(x, 0.0);
            if !px.is_finite() || px < area.x || px > area.x + area.width {
                continue;
            }
            renderer.draw_line_clipped(
                px,
                top,
                px,
                bottom,
                color,
                width,
                LineStyle::Dashed,
                clip_rect,
            )?;
        }

        Ok(())
    }
}

// =============================================================================
// KDE Computation
// =============================================================================

/// Compute KDE for plotting
///
/// # Arguments
/// * `data` - Input data
/// * `config` - KDE configuration
///
/// # Returns
/// `KdeData` for rendering
///
/// # Example
///
/// ```rust
/// use ruviz::plots::distribution::{KdeConfig, compute_kde};
///
/// let data = vec![1.0, 2.0, 2.5, 3.0, 3.5, 4.0];
/// let kde_data = compute_kde(&data, &KdeConfig::default());
///
/// assert!(!kde_data.x.is_empty());
/// ```
pub fn compute_kde(data: &[f64], config: &KdeConfig) -> KdeData {
    if data.is_empty() {
        return KdeData {
            x: vec![],
            y: vec![],
            bandwidth: 0.0,
            cumulative: false,
            config: config.clone(),
        };
    }

    // Resolving here rather than letting `kde_1d` apply its own `None` fallback
    // keeps one bandwidth rule for both kernel-density plot types.
    let kde = kde_1d(
        data,
        Some(config.bandwidth.resolve(data)),
        Some(config.n_points),
    );

    let (x, y) = if config.cumulative {
        // Convert to cumulative distribution
        let mut cumulative = Vec::with_capacity(kde.density.len());
        let mut sum = 0.0;
        let dx = if kde.x.len() > 1 {
            kde.x[1] - kde.x[0]
        } else {
            1.0
        };

        for d in &kde.density {
            sum += d * dx;
            cumulative.push(sum);
        }

        // Normalize to [0, 1]
        if let Some(&max) = cumulative.last()
            && max > 0.0
        {
            for c in &mut cumulative {
                *c /= max;
            }
        }

        (kde.x, cumulative)
    } else {
        (kde.x, kde.density)
    };

    // Apply clipping if specified
    let (x, y) = if let Some((min, max)) = config.clip {
        let mut clipped_x = Vec::new();
        let mut clipped_y = Vec::new();

        for (xi, yi) in x.iter().zip(y.iter()) {
            if *xi >= min && *xi <= max {
                clipped_x.push(*xi);
                clipped_y.push(*yi);
            }
        }

        (clipped_x, clipped_y)
    } else {
        (x, y)
    };

    KdeData {
        x,
        y,
        bandwidth: kde.bandwidth,
        cumulative: config.cumulative,
        config: config.clone(),
    }
}

/// Deprecated alias for backward compatibility
#[deprecated(since = "0.1.0", note = "Use compute_kde instead")]
pub fn compute_kde_plot(data: &[f64], config: &KdeConfig) -> KdeData {
    compute_kde(data, config)
}

/// Generate polygon vertices for filled KDE plot
///
/// Returns vertices that close the polygon to baseline
pub fn kde_fill_polygon(kde_data: &KdeData, baseline: f64) -> Vec<(f64, f64)> {
    if kde_data.x.is_empty() {
        return vec![];
    }

    let n = kde_data.x.len();
    let mut polygon = Vec::with_capacity(n * 2 + 2);

    // Top edge (KDE curve)
    for i in 0..n {
        polygon.push((kde_data.x[i], kde_data.y[i]));
    }

    // Bottom edge (baseline)
    polygon.push((kde_data.x[n - 1], baseline));
    polygon.push((kde_data.x[0], baseline));

    polygon
}

// =============================================================================
// Trait Implementations
// =============================================================================

/// Marker type for KDE plot computation
///
/// This empty struct is used to implement [`PlotCompute`] for KDE plots.
pub struct Kde;

impl PlotCompute for Kde {
    type Input<'a> = &'a [f64];
    type Config = KdeConfig;
    type Output = KdeData;

    fn compute(input: Self::Input<'_>, config: &Self::Config) -> Result<Self::Output> {
        Ok(compute_kde(input, config))
    }
}

impl PlotData for KdeData {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        if self.x.is_empty() {
            return ((0.0, 1.0), (0.0, 1.0));
        }

        let x_min = self.x.iter().copied().fold(f64::INFINITY, f64::min);
        let x_max = self.x.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        // Density always starts at 0
        let y_min = 0.0;
        let y_max = self.y.iter().copied().fold(f64::NEG_INFINITY, f64::max);

        ((x_min, x_max), (y_min, y_max * 1.05)) // 5% padding on top
    }

    fn is_empty(&self) -> bool {
        self.x.is_empty()
    }
}

impl KdeData {
    /// The density curve, split into the runs the axis scales can place.
    ///
    /// On a logarithmic axis the evaluation grid can run past the axis — it
    /// extends a few bandwidths beyond the data, which on a log x axis reaches
    /// zero and below. Those samples have no position, so the curve breaks
    /// there rather than being drawn through a fabricated coordinate.
    pub(crate) fn projected_runs(&self, area: &PlotArea) -> Vec<Vec<(f32, f32)>> {
        area.project_subpaths(self.x.iter().zip(self.y.iter()).map(|(&x, &y)| (x, y)))
    }

    /// Close one curve run down to the fill baseline.
    pub(crate) fn fill_polygon(run: &[(f32, f32)], baseline_y: f32) -> Vec<(f32, f32)> {
        let mut polygon = Vec::with_capacity(run.len() + 2);
        polygon.push((run[0].0, baseline_y));
        polygon.extend_from_slice(run);
        polygon.push((run[run.len() - 1].0, baseline_y));
        polygon
    }

    /// Draw the curve, its fill and its vertical markers.
    ///
    /// `render` and `render_styled` differ only in how they resolve colour and
    /// line width, so the geometry lives here once.
    fn draw(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        line_color: Color,
        fill_color: Color,
        line_width: f32,
    ) -> Result<()> {
        let runs = self.projected_runs(area);
        if runs.is_empty() {
            return Ok(());
        }

        if self.config.fill {
            let baseline_y = area.fill_baseline_y();
            for run in &runs {
                renderer.draw_filled_polygon(&Self::fill_polygon(run, baseline_y), fill_color)?;
            }
        }

        for run in &runs {
            renderer.draw_polyline(run, line_color, line_width, LineStyle::Solid)?;
        }

        self.draw_vertical_lines(renderer, area, line_color)
    }
}

impl PlotRender for KdeData {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        _theme: &Theme,
        color: Color,
    ) -> Result<()> {
        if self.is_empty() {
            return Ok(());
        }

        let line_width = renderer
            .render_scale()
            .points_to_pixels(self.config.line_width);
        self.draw(
            renderer,
            area,
            color,
            color.with_alpha(self.config.fill_alpha),
            line_width,
        )
    }

    fn render_styled(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        color: Color,
        alpha: f32,
        line_width: Option<f32>,
    ) -> Result<()> {
        if self.is_empty() {
            return Ok(());
        }

        let resolver = StyleResolver::new(theme);
        let actual_line_width = renderer.render_scale().points_to_pixels(
            line_width.unwrap_or_else(|| resolver.line_width(Some(self.config.line_width))),
        );
        let alpha = alpha.clamp(0.0, 1.0);
        let actual_color = color.with_alpha((f32::from(color.a) / 255.0) * alpha);
        let fill_color =
            color.with_alpha((f32::from(color.a) / 255.0) * self.config.fill_alpha * alpha);

        self.draw(renderer, area, actual_color, fill_color, actual_line_width)
    }
}

/// Configuration for 2D KDE (density heatmap)
#[derive(Debug, Clone)]
pub struct Kde2dPlotConfig {
    /// Bandwidth for x dimension
    pub bandwidth_x: Option<f64>,
    /// Bandwidth for y dimension
    pub bandwidth_y: Option<f64>,
    /// Grid resolution
    pub grid_size: usize,
    /// Number of contour levels
    pub levels: usize,
    /// Whether to fill contours
    pub fill: bool,
    /// Colormap name
    pub cmap: String,
    /// Show scatter points
    pub show_points: bool,
    /// Point size
    pub point_size: f32,
    /// Point alpha
    pub point_alpha: f32,
}

impl Default for Kde2dPlotConfig {
    fn default() -> Self {
        Self {
            bandwidth_x: None,
            bandwidth_y: None,
            grid_size: 100,
            levels: 10,
            fill: true,
            cmap: "viridis".to_string(),
            show_points: false,
            point_size: 3.0,
            point_alpha: 0.5,
        }
    }
}

impl Kde2dPlotConfig {
    /// Create new config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set grid size
    pub fn grid_size(mut self, size: usize) -> Self {
        self.grid_size = size.max(10);
        self
    }

    /// Set number of contour levels
    pub fn levels(mut self, levels: usize) -> Self {
        self.levels = levels.max(2);
        self
    }

    /// Enable fill
    pub fn fill(mut self, fill: bool) -> Self {
        self.fill = fill;
        self
    }

    /// Show scatter points
    pub fn show_points(mut self, show: bool) -> Self {
        self.show_points = show;
        self
    }

    /// Set colormap.
    ///
    /// Accepts a name such as `"viridis"` or a [`ColorMap`](crate::render::ColorMap) value.
    pub fn cmap(mut self, cmap: impl Into<ColorMapSpec>) -> Self {
        self.cmap = cmap.into().into_name();
        self
    }
}

/// Result of 2D kernel density estimation for plotting
#[derive(Debug, Clone)]
pub struct Kde2dPlotData {
    /// X grid coordinates
    pub x: Vec<f64>,
    /// Y grid coordinates
    pub y: Vec<f64>,
    /// Density values as 2D array (row-major)
    pub density: Vec<Vec<f64>>,
}

/// Compute 2D KDE for density plot
pub fn compute_kde_2d_plot(x: &[f64], y: &[f64], config: &Kde2dPlotConfig) -> Kde2dPlotData {
    let bandwidth = match (config.bandwidth_x, config.bandwidth_y) {
        (Some(bx), Some(by)) => Some((bx, by)),
        _ => None,
    };
    let (x_grid, y_grid, density) = kde_2d(x, y, bandwidth, Some(config.grid_size));

    Kde2dPlotData {
        x: x_grid,
        y: y_grid,
        density,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plots::traits::PlotCompute;

    #[test]
    fn test_kde_basic() {
        let data = vec![1.0, 2.0, 2.5, 3.0, 3.5, 4.0];
        let config = KdeConfig::default();
        let kde_data = compute_kde(&data, &config);

        assert!(!kde_data.x.is_empty());
        assert_eq!(kde_data.x.len(), kde_data.y.len());
        assert!(!kde_data.cumulative);
    }

    #[test]
    fn test_kde_cumulative() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let config = KdeConfig::default().cumulative(true);
        let kde_data = compute_kde(&data, &config);

        assert!(kde_data.cumulative);
        // Cumulative should be monotonically increasing
        for i in 1..kde_data.y.len() {
            assert!(kde_data.y[i] >= kde_data.y[i - 1] - 1e-10);
        }
        // Last value should be approximately 1.0
        if let Some(&last) = kde_data.y.last() {
            assert!((last - 1.0).abs() < 0.01);
        }
    }

    #[test]
    fn test_kde_clipped() {
        let data = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
        let config = KdeConfig::default().clip(1.0, 4.0);
        let kde_data = compute_kde(&data, &config);

        for &xi in &kde_data.x {
            assert!((1.0..=4.0).contains(&xi));
        }
    }

    #[test]
    fn test_kde_fill_polygon() {
        let kde_data = KdeData {
            x: vec![0.0, 1.0, 2.0],
            y: vec![0.1, 0.5, 0.2],
            bandwidth: 0.5,
            cumulative: false,
            config: KdeConfig::default(),
        };

        let polygon = kde_fill_polygon(&kde_data, 0.0);
        assert_eq!(polygon.len(), 5); // 3 points + 2 baseline points
    }

    #[test]
    fn test_kde_empty() {
        let data: Vec<f64> = vec![];
        let config = KdeConfig::default();
        let kde_data = compute_kde(&data, &config);

        assert!(kde_data.x.is_empty());
        assert!(kde_data.y.is_empty());
    }

    // ==========================================================================
    // Trait Implementation Tests
    // ==========================================================================

    #[test]
    fn test_kde_plot_compute_trait() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let config = KdeConfig::default();

        let result = Kde::compute(&data, &config);
        assert!(result.is_ok());

        let kde_data = result.unwrap();
        assert!(!kde_data.is_empty());
        assert_eq!(kde_data.x.len(), config.n_points);
    }

    #[test]
    fn test_kde_plot_data_trait() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let config = KdeConfig::default();
        let kde_data = compute_kde(&data, &config);

        // Test data_bounds
        let ((x_min, x_max), (y_min, y_max)) = kde_data.data_bounds();
        assert!(x_min < x_max);
        assert_eq!(y_min, 0.0); // Density starts at 0
        assert!(y_max > 0.0);

        // Test is_empty
        assert!(!kde_data.is_empty());

        // Test empty data
        let empty_data: Vec<f64> = vec![];
        let empty_kde = compute_kde(&empty_data, &config);
        assert!(empty_kde.is_empty());
    }

    #[test]
    fn test_kde_config_implements_plot_config() {
        // Verify that KdeConfig implements PlotConfig (compile-time check)
        fn accepts_plot_config<T: PlotConfig>(_: &T) {}
        let config = KdeConfig::default();
        accepts_plot_config(&config);
    }

    #[test]
    fn test_kde_config_builder_methods() {
        let config = KdeConfig::new()
            .bandwidth(0.5)
            .n_points(100)
            .fill(true)
            .fill_alpha(0.5)
            .cumulative(false)
            .clip(0.0, 10.0)
            .vertical_line(5.0);

        assert_eq!(config.bandwidth, BandwidthMethod::Fixed(0.5));
        assert_eq!(config.n_points, 100);
        assert!(config.fill);
        assert_eq!(config.fill_alpha, 0.5);
        assert!(!config.cumulative);
        assert_eq!(config.clip, Some((0.0, 10.0)));
        assert_eq!(config.vertical_lines.len(), 1);
    }

    #[test]
    fn kde_and_violin_spell_bandwidth_the_same_way() {
        use crate::plots::distribution::ViolinConfig;

        // Both kernel-density plot types take a rule...
        assert_eq!(
            KdeConfig::new()
                .bandwidth(BandwidthMethod::Silverman)
                .bandwidth,
            ViolinConfig::new()
                .bandwidth(BandwidthMethod::Silverman)
                .bandwidth,
        );
        // ...and both take a bare number for a fixed bandwidth.
        assert_eq!(
            KdeConfig::new().bandwidth(0.5).bandwidth,
            ViolinConfig::new().bandwidth(0.5).bandwidth,
        );
        assert_eq!(
            KdeConfig::new().bandwidth(0.5).bandwidth,
            BandwidthMethod::Fixed(0.5)
        );
    }

    #[test]
    fn default_kde_bandwidth_still_resolves_to_scotts_rule() {
        // `KdeConfig.bandwidth` used to be `Option<f64>` with `None` meaning
        // "let kde_1d apply Scott's rule". The enum default must produce the
        // identical number, or every unconfigured KDE plot changes shape.
        let data: Vec<f64> = (0..64).map(|i| (i as f64 * 0.37).sin()).collect();
        assert_eq!(
            KdeConfig::default().bandwidth.resolve(&data),
            crate::stats::kde::scotts_rule(&data),
        );
    }

    // ------------------------------------------------------------------
    // vertical_lines (plan item 2.4)
    // ------------------------------------------------------------------

    fn render_kde(config: KdeConfig) -> crate::core::Result<crate::core::plot::Image> {
        let data: Vec<f64> = (0..80).map(|i| (i as f64) / 8.0).collect();
        let kde_data = compute_kde(&data, &config);
        let mut renderer = SkiaRenderer::new(200, 200, Theme::default())?;
        let ((x_min, x_max), (y_min, y_max)) = kde_data.data_bounds();
        let area = PlotArea::new(0.0, 0.0, 200.0, 200.0, x_min, x_max, y_min, y_max);
        kde_data.render(
            &mut renderer,
            &area,
            &Theme::default(),
            Color::from_rgb(200, 0, 0),
        )?;
        Ok(renderer.into_image())
    }

    #[test]
    fn test_vertical_lines_change_the_rendered_image() {
        let without = render_kde(KdeConfig::new().fill(false)).unwrap();
        let with = render_kde(KdeConfig::new().fill(false).vertical_line(5.0)).unwrap();

        assert_ne!(
            without.pixels, with.pixels,
            "KdeConfig::vertical_line produced a byte-identical image"
        );
    }

    #[test]
    fn test_more_vertical_lines_draw_more_ink() {
        fn ink(image: &crate::core::plot::Image) -> usize {
            image
                .pixels
                .chunks_exact(4)
                .filter(|p| p[3] > 0 && (p[0] < 250 || p[1] < 250 || p[2] < 250))
                .count()
        }

        let one = render_kde(KdeConfig::new().fill(false).vertical_line(3.0)).unwrap();
        let three =
            render_kde(KdeConfig::new().fill(false).vertical_lines([2.0, 5.0, 8.0])).unwrap();

        assert!(
            ink(&three) > ink(&one),
            "three reference lines drew no more ink than one"
        );
    }

    #[test]
    fn test_offscreen_and_nonfinite_vertical_lines_are_skipped() {
        let baseline = render_kde(KdeConfig::new().fill(false)).unwrap();
        let offscreen = render_kde(KdeConfig::new().fill(false).vertical_lines([
            -1_000.0,
            1_000.0,
            f64::NAN,
            f64::INFINITY,
        ]))
        .unwrap();

        assert_eq!(
            baseline.pixels, offscreen.pixels,
            "an off-screen reference line was clamped onto the plot border"
        );
    }

    #[test]
    fn test_vertical_lines_setter_replaces_the_whole_set() {
        let config = KdeConfig::new().vertical_line(1.0).vertical_lines([7.0]);
        assert_eq!(config.vertical_lines, vec![7.0]);
    }

    // Backward compatibility tests
    #[test]
    #[allow(deprecated)]
    fn test_deprecated_type_aliases() {
        // Test that deprecated aliases still work
        let _config: KdePlotConfig = KdeConfig::default();
        let data = vec![1.0, 2.0, 3.0];
        let _kde_data: KdePlotData = compute_kde_plot(&data, &_config);
    }
}