1use crate::canvas::{Canvas, Marker};
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::util::{darken, dim_text, format_tick, nice_bounds, nice_ticks, pick};
7use ratatui::{
8 buffer::Buffer,
9 layout::Rect,
10 style::{Color, Style},
11 widgets::Block,
12};
13
14#[derive(Debug, Clone, PartialEq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct ViolinGroup {
18 pub label: String,
20 pub samples: Vec<f64>,
22 pub color: Option<Color>,
24}
25
26impl ViolinGroup {
27 pub fn new(label: impl Into<String>, samples: impl IntoIterator<Item = f64>) -> Self {
29 Self {
30 label: label.into(),
31 samples: samples.into_iter().collect(),
32 color: None,
33 }
34 }
35
36 pub fn color(mut self, c: Color) -> Self {
38 self.color = Some(c);
39 self
40 }
41}
42
43#[derive(Debug, Clone, Default)]
57pub struct ViolinChart {
58 groups: Vec<ViolinGroup>,
59 bandwidth: Option<f64>,
60 show_box: bool,
61 marker: Marker,
62 theme: Option<Theme>,
63 base: Option<Style>,
64 block: Option<Block<'static>>,
65}
66
67fn quantile(sorted: &[f64], q: f64) -> f64 {
68 let pos = q * (sorted.len() - 1) as f64;
69 let (i, f) = (pos.floor() as usize, pos.fract());
70 let j = (i + 1).min(sorted.len() - 1);
71 sorted[i] * (1.0 - f) + sorted[j] * f
72}
73
74impl ViolinChart {
75 pub fn new(groups: impl IntoIterator<Item = ViolinGroup>) -> Self {
77 Self {
78 groups: groups.into_iter().collect(),
79 show_box: true,
80 ..Self::default()
81 }
82 }
83
84 opt_setter!(
85 bandwidth: f64
87 );
88 setter!(
89 show_box: bool
91 );
92 setter!(
93 marker: Marker
95 );
96 theme_setter!(
97 theme
99 );
100 base_style_setter!(base);
101 block_setter!(block, 'static);
102
103 fn render_into(&self, area: Rect, buf: &mut Buffer) {
104 let area = area.intersection(buf.area);
105 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
106 if inner.width < 8 || inner.height < 4 {
107 return;
108 }
109 let data: Vec<(usize, &ViolinGroup, Vec<f64>)> = self
110 .groups
111 .iter()
112 .enumerate()
113 .filter_map(|(i, g)| {
114 let mut s: Vec<f64> = g
115 .samples
116 .iter()
117 .copied()
118 .filter(|v| v.is_finite())
119 .collect();
120 s.sort_by(f64::total_cmp);
121 (!s.is_empty()).then_some((i, g, s))
122 })
123 .collect();
124 if data.is_empty() {
125 return;
126 }
127 let lo = data.iter().map(|d| d.2[0]).fold(f64::MAX, f64::min);
128 let hi = data
129 .iter()
130 .map(|d| *d.2.last().unwrap())
131 .fold(f64::MIN, f64::max);
132 let (lo, hi) = nice_bounds(lo, hi, 5);
133 let span = (hi - lo).max(f64::EPSILON);
134 let (dim, text) = dim_text(&self.theme);
135
136 let ticks = nice_ticks(lo, hi, (inner.height as usize / 3).max(2));
137 let step = if ticks.len() >= 2 {
138 ticks[1] - ticks[0]
139 } else {
140 1.0
141 };
142 let labels: Vec<String> = ticks.iter().map(|t| format_tick(*t, step)).collect();
143 let gutter = (labels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
144 .min(inner.width / 2);
145 let plot = Rect::new(
146 inner.x + gutter,
147 inner.y,
148 inner.width - gutter,
149 inner.height - 1,
150 );
151 if plot.width < 2 || plot.height < 2 {
152 return;
153 }
154 for (t, l) in ticks.iter().zip(&labels) {
155 let f = ((t - lo) / span).clamp(0.0, 1.0);
156 let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
157 let w = l.chars().count() as u16;
158 put_str(
159 buf,
160 inner.x + gutter.saturating_sub(w + 1),
161 y,
162 plot.x,
163 l,
164 dim,
165 );
166 for x in plot.x..plot.right() {
167 buf[(x, y)].set_char('┈').set_style(dim);
168 }
169 }
170
171 let mut cv = Canvas::new(plot.width, plot.height, self.marker);
172 let (pw, ph) = (cv.px_w(), cv.px_h());
173 let slot = pw / data.len() as i32;
174 let ypx = |v: f64| ((1.0 - (v - lo) / span) * (ph - 1) as f64).round() as i32;
175 for (k, (i, g, s)) in data.iter().enumerate() {
176 let c = g.color.unwrap_or_else(|| pick(&self.theme, *i));
177 let fill = darken(c, 0.45);
178 let cx = slot * k as i32 + slot / 2;
179 let half = ((slot / 2) as f64 * 0.85) as i32;
180 let n = s.len();
181 let mean = s.iter().sum::<f64>() / n as f64;
182 let sd = (s.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n as f64).sqrt();
183 let h = self
184 .bandwidth
185 .filter(|b| *b > 0.0)
186 .unwrap_or_else(|| {
187 let bw = 1.06 * sd * (n as f64).powf(-0.2);
188 if bw > 0.0 {
189 bw
190 } else {
191 span / 20.0
192 }
193 })
194 .max(span * 1e-6);
195 let stride = (n / 2000).max(1);
197 let pts: Vec<f64> = s.iter().step_by(stride).copied().collect();
198 let dens: Vec<f64> = (0..ph)
199 .map(|py| {
200 let v = hi - span * py as f64 / (ph - 1).max(1) as f64;
201 pts.iter()
202 .map(|x| (-0.5 * ((v - x) / h).powi(2)).exp())
203 .sum::<f64>()
204 })
205 .collect();
206 let dmax = dens
207 .iter()
208 .copied()
209 .fold(0.0, f64::max)
210 .max(f64::MIN_POSITIVE);
211 let (smin, smax) = (ypx(s[n - 1]), ypx(s[0]));
212 for (py, d) in dens.iter().enumerate() {
213 let py = py as i32;
214 if py < smin - 2 || py > smax + 2 {
215 continue;
216 }
217 let hw = (d / dmax * half as f64).round() as i32;
218 if hw <= 0 {
219 continue;
220 }
221 for px in cx - hw..=cx + hw {
222 cv.set(px, py, fill);
223 }
224 cv.set(cx - hw, py, c);
225 cv.set(cx + hw, py, c);
226 }
227 if self.show_box {
228 let (q1, med, q3) = (quantile(s, 0.25), quantile(s, 0.5), quantile(s, 0.75));
229 for py in ypx(q3)..=ypx(q1) {
230 cv.set(cx, py, Color::White);
231 cv.set(cx + 1, py, Color::White);
232 }
233 let m = ypx(med);
234 for (dx, dy) in [
235 (0, 0),
236 (1, 0),
237 (-1, 0),
238 (2, 0),
239 (0, 1),
240 (1, 1),
241 (0, -1),
242 (1, -1),
243 ] {
244 cv.set(cx + dx, m + dy, c);
245 }
246 }
247 }
248 cv.render(buf, plot);
249 let slot_w = plot.width / data.len() as u16;
250 for (k, (_, g, _)) in data.iter().enumerate() {
251 let l: String = g.label.chars().take(slot_w as usize).collect();
252 let x =
253 plot.x + slot_w * k as u16 + slot_w.saturating_sub(l.chars().count() as u16) / 2;
254 put_str(buf, x, inner.bottom() - 1, inner.right(), &l, text);
255 }
256 }
257}
258
259widget_impls!(ViolinChart);
260
261#[cfg(feature = "theme")]
262impl tui_nuances::Themed for ViolinChart {
263 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
264 self.theme(theme)
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271 use ratatui::widgets::Widget;
272
273 fn render(c: &ViolinChart, w: u16, h: u16) -> Buffer {
274 let a = Rect::new(0, 0, w, h);
275 let mut b = Buffer::empty(a);
276 c.render(a, &mut b);
277 b
278 }
279
280 fn bell(mu: f64, sd: f64) -> Vec<f64> {
281 (0..200)
282 .map(|i| {
283 mu + sd * (((i as f64) * 0.618).fract() * 2.0 - 1.0) * 1.7
284 + sd * ((i % 7) as f64 - 3.0) * 0.2
285 })
286 .collect()
287 }
288
289 fn chart() -> ViolinChart {
290 ViolinChart::new([
291 ViolinGroup::new("a", bell(5.0, 1.0)).color(Color::Red),
292 ViolinGroup::new("b", bell(8.0, 2.0)).color(Color::Blue),
293 ])
294 }
295
296 #[test]
297 fn draws_groups_in_their_colors_with_labels() {
298 let b = render(&chart(), 60, 20);
299 let t: String = b.content().iter().map(|c| c.symbol()).collect();
300 assert!(t.contains('a') && t.contains('b'));
301 assert!(b.content().iter().any(|c| c.fg == Color::Red));
302 assert!(b.content().iter().any(|c| c.fg == Color::Blue));
303 }
304
305 #[test]
306 fn wider_spread_covers_more_cells() {
307 let count = |sd: f64| {
308 let c = ViolinChart::new([ViolinGroup::new("x", bell(5.0, sd)).color(Color::Red)])
309 .show_box(false);
310 render(&c, 40, 20)
311 .content()
312 .iter()
313 .filter(|c| c.symbol() != " " && c.fg != Color::DarkGray && c.fg != Color::Reset)
314 .count()
315 };
316 assert!(count(3.0) > count(0.3));
317 }
318
319 #[test]
320 fn box_toggle_changes_output() {
321 let on = render(&chart(), 60, 20);
322 let off = render(&chart().show_box(false), 60, 20);
323 assert_ne!(on, off);
324 assert!(on.content().iter().any(|c| c.fg == Color::White));
325 }
326
327 #[test]
328 fn explicit_bandwidth_smooths() {
329 let narrow = render(&chart().bandwidth(0.05), 60, 20);
330 let wide = render(&chart().bandwidth(3.0), 60, 20);
331 assert_ne!(narrow, wide);
332 }
333
334 #[test]
335 fn degenerate_inputs_do_not_panic() {
336 let c = ViolinChart::new([
337 ViolinGroup::new("nan", [f64::NAN, f64::INFINITY]),
338 ViolinGroup::new("one", [3.0]),
339 ViolinGroup::new("same", [2.0, 2.0, 2.0]),
340 ViolinGroup::new("big", [-1e300, 1e300]),
341 ]);
342 for (w, h) in [(0, 0), (1, 1), (8, 4), (3, 40), (200, 60)] {
343 render(&c, w, h);
344 render(&chart(), w, h);
345 }
346 render(&ViolinChart::new([]), 40, 10);
347 }
348}