1use crate::aes::Aesthetic;
2use crate::coord::Coord;
3use crate::data::{DataFrame, Value};
4use crate::position::identity::PositionIdentity;
5use crate::position::Position;
6use crate::render::backend::{DrawBackend, FontFace, LineStyle, Linetype, TextAnchor, TextStyle};
7use crate::render::RenderError;
8use crate::scale::ScaleSet;
9use crate::stat::identity::StatIdentity;
10use crate::stat::Stat;
11use crate::theme::Theme;
12
13use super::{Geom, GeomParams};
14
15pub struct GeomBracket {
20 pub color: (u8, u8, u8),
21 pub line_width: f64,
22 pub tip_length: f64,
24 pub label_size: f64,
26}
27
28impl Default for GeomBracket {
29 fn default() -> Self {
30 GeomBracket {
31 color: (0, 0, 0),
32 line_width: 1.0,
33 tip_length: 8.0,
34 label_size: 12.0,
35 }
36 }
37}
38
39impl Geom for GeomBracket {
40 fn draw(
41 &self,
42 data: &DataFrame,
43 coord: &dyn Coord,
44 scales: &ScaleSet,
45 _theme: &Theme,
46 backend: &mut dyn DrawBackend,
47 ) -> Result<(), RenderError> {
48 let xmin_col = data
49 .column("xmin")
50 .ok_or(RenderError::MissingAesthetic("xmin".into()))?;
51 let xmax_col = data
52 .column("xmax")
53 .ok_or(RenderError::MissingAesthetic("xmax".into()))?;
54 let y_col = data
55 .column("y")
56 .ok_or(RenderError::MissingAesthetic("y".into()))?;
57 let label_col = data.column("label");
58
59 let plot_area = backend.plot_area();
60 let x_scale = scales.get(&Aesthetic::X);
61 let y_scale = scales.get(&Aesthetic::Y);
62
63 for i in 0..data.nrows() {
64 let nxmin = x_scale.map(|s| s.map(&xmin_col[i])).unwrap_or(0.0);
65 let nxmax = x_scale.map(|s| s.map(&xmax_col[i])).unwrap_or(0.0);
66 let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
67
68 let (px_min, py) = coord.transform((nxmin, ny), &plot_area);
69 let (px_max, _) = coord.transform((nxmax, ny), &plot_area);
70
71 let label_text = label_col.map(|lc| lc[i].to_group_key()).unwrap_or_default();
74 let comparison = format!(
75 "{} vs {}",
76 super::tip_value(&xmin_col[i]),
77 super::tip_value(&xmax_col[i])
78 );
79 let series = data
80 .column(BRACKET_SERIES_COL)
81 .and_then(|c| c.get(i))
82 .filter(|v| !v.is_na())
83 .map(super::tip_value)
84 .unwrap_or_else(|| comparison.clone());
85 let value = data
86 .column(BRACKET_P_COL)
87 .and_then(|c| c.get(i))
88 .and_then(super::raw_value);
89 let tooltip = if label_text.is_empty() {
90 comparison.clone()
91 } else {
92 format!("{comparison}: {label_text}")
93 };
94 super::set_mark(
95 backend,
96 Some(tooltip),
97 Some(comparison),
98 Some(series),
99 value,
100 );
101
102 let tip = self.tip_length;
105 backend.draw_line(
106 &[
107 (px_min, py + tip),
108 (px_min, py),
109 (px_max, py),
110 (px_max, py + tip),
111 ],
112 &LineStyle {
113 color: self.color,
114 alpha: 1.0,
115 width: self.line_width,
116 linetype: Linetype::Solid,
117 },
118 )?;
119 super::clear_mark(backend);
120
121 if let Some(lc) = label_col {
123 let text = lc[i].to_group_key();
124 if !text.is_empty() {
125 let cx = (px_min + px_max) / 2.0;
126 backend.draw_text(
127 &text,
128 (cx, py - self.label_size * 0.3 - 2.0),
129 &TextStyle {
130 color: self.color,
131 size: self.label_size,
132 anchor: TextAnchor::Middle,
133 angle: 0.0,
134 family: None,
135 face: FontFace::Plain,
136 },
137 )?;
138 }
139 }
140 }
141
142 Ok(())
143 }
144
145 fn required_aes(&self) -> Vec<Aesthetic> {
146 vec![Aesthetic::Xmin, Aesthetic::Xmax, Aesthetic::Y]
147 }
148
149 fn default_stat(&self) -> Box<dyn Stat> {
150 Box::new(StatIdentity)
151 }
152 fn default_position(&self) -> Box<dyn Position> {
153 Box::new(PositionIdentity)
154 }
155 fn default_params(&self) -> GeomParams {
156 GeomParams::default()
157 }
158 fn name(&self) -> &str {
159 "bracket"
160 }
161
162 fn set_series_color(&mut self, color: (u8, u8, u8)) {
163 self.color = color;
164 }
165}
166
167pub(crate) const BRACKET_P_COL: &str = ".bracket_p";
169pub(crate) const BRACKET_SERIES_COL: &str = ".bracket_series";
172
173#[derive(Clone)]
220pub struct BracketTable {
221 pub label: Option<String>,
223 pub group1: String,
225 pub group2: String,
227 pub p_column: Option<String>,
229 pub y_position: String,
231 pub step_increase: f64,
233 pub hide_ns: bool,
236 pub cutpoints: Vec<(f64, String)>,
240 pub geom: GeomBracketStyle,
242}
243
244#[derive(Clone, Copy, Debug)]
247pub struct GeomBracketStyle {
248 pub color: (u8, u8, u8),
249 pub line_width: f64,
250 pub tip_length: f64,
251 pub label_size: f64,
252}
253
254impl Default for GeomBracketStyle {
255 fn default() -> Self {
256 let g = GeomBracket::default();
257 GeomBracketStyle {
258 color: g.color,
259 line_width: g.line_width,
260 tip_length: g.tip_length,
261 label_size: g.label_size,
262 }
263 }
264}
265
266impl From<GeomBracketStyle> for GeomBracket {
267 fn from(s: GeomBracketStyle) -> Self {
268 GeomBracket {
269 color: s.color,
270 line_width: s.line_width,
271 tip_length: s.tip_length,
272 label_size: s.label_size,
273 }
274 }
275}
276
277impl Default for BracketTable {
278 fn default() -> Self {
279 BracketTable {
280 label: None,
281 group1: "group1".into(),
282 group2: "group2".into(),
283 p_column: None,
284 y_position: "y_position".into(),
285 step_increase: 0.12,
286 hide_ns: false,
287 cutpoints: vec![
288 (1e-4, "****".into()),
289 (1e-3, "***".into()),
290 (1e-2, "**".into()),
291 (0.05, "*".into()),
292 (f64::INFINITY, "ns".into()),
293 ],
294 geom: GeomBracketStyle::default(),
295 }
296 }
297}
298
299impl BracketTable {
300 pub fn new() -> Self {
301 Self::default()
302 }
303
304 pub fn label(mut self, template: &str) -> Self {
306 self.label = Some(template.to_string());
307 self
308 }
309
310 pub fn stars(self) -> Self {
312 self.label("{p.signif}")
313 }
314
315 pub fn p_column(mut self, col: &str) -> Self {
317 self.p_column = Some(col.to_string());
318 self
319 }
320
321 pub fn groups(mut self, group1: &str, group2: &str) -> Self {
323 self.group1 = group1.to_string();
324 self.group2 = group2.to_string();
325 self
326 }
327
328 pub fn y_position(mut self, col: &str) -> Self {
330 self.y_position = col.to_string();
331 self
332 }
333
334 pub fn step_increase(mut self, step: f64) -> Self {
336 self.step_increase = step;
337 self
338 }
339
340 pub fn hide_ns(mut self, hide: bool) -> Self {
342 self.hide_ns = hide;
343 self
344 }
345
346 pub fn cutpoints(mut self, cutpoints: &[(f64, &str)]) -> Self {
348 self.cutpoints = cutpoints.iter().map(|(c, s)| (*c, s.to_string())).collect();
349 self
350 }
351
352 pub fn style(mut self, style: GeomBracketStyle) -> Self {
354 self.geom = style;
355 self
356 }
357
358 pub fn signif(&self, p: f64) -> String {
360 if !p.is_finite() {
361 return String::new();
362 }
363 self.cutpoints
364 .iter()
365 .find(|(c, _)| p <= *c)
366 .map(|(_, s)| s.clone())
367 .unwrap_or_default()
368 }
369
370 fn is_ns(&self, p: f64) -> bool {
372 match self.cutpoints.len() {
373 0 => false,
374 n => {
375 let below = if n >= 2 {
376 self.cutpoints[n - 2].0
377 } else {
378 f64::NEG_INFINITY
379 };
380 p.is_finite() && p > below
381 }
382 }
383 }
384
385 pub(crate) fn resolve(
390 &self,
391 table: &DataFrame,
392 x_levels: &[String],
393 y_range: Option<(f64, f64)>,
394 warnings: &mut Vec<String>,
395 ) -> Option<DataFrame> {
396 const WHO: &str = "geom_bracket";
397 if let Err(e) = table.validate() {
398 warnings.push(format!(
399 "{WHO}: test table rejected ({e}); no brackets drawn"
400 ));
401 return None;
402 }
403 let (Some(g1), Some(g2)) = (table.column(&self.group1), table.column(&self.group2)) else {
404 warnings.push(format!(
405 "{WHO}: test table needs '{}' and '{}' columns; no brackets drawn",
406 self.group1, self.group2
407 ));
408 return None;
409 };
410 let p_of = |i: usize| -> Option<f64> {
411 let get = |c: &str| {
412 table
413 .column(c)
414 .and_then(|col| col.get(i))
415 .and_then(|v| v.as_f64())
416 .filter(|p| !p.is_nan())
417 };
418 match &self.p_column {
419 Some(c) => get(c),
420 None => get("p_adj").or_else(|| get("p_value")),
421 }
422 };
423
424 let mut rows: Vec<(usize, f64)> = Vec::new(); let (mut missing, mut unknown, mut ns) = (0usize, Vec::new(), 0usize);
426 for i in 0..table.nrows() {
427 let (a, b) = (&g1[i], &g2[i]);
428 if a.is_na() || b.is_na() {
429 missing += 1;
430 continue;
431 }
432 if !x_levels.is_empty() {
433 let bad: Vec<String> = [a, b]
434 .iter()
435 .map(|v| v.to_group_key())
436 .filter(|k| !x_levels.contains(k))
437 .collect();
438 if !bad.is_empty() {
439 unknown.extend(bad);
440 continue;
441 }
442 }
443 let p = p_of(i).unwrap_or(f64::NAN);
444 if self.hide_ns && self.is_ns(p) {
445 ns += 1;
446 continue;
447 }
448 rows.push((i, p));
449 }
450 if missing > 0 {
451 warnings.push(format!(
452 "{WHO}: removed {missing} row{} with a missing group",
453 if missing == 1 { "" } else { "s" }
454 ));
455 }
456 if !unknown.is_empty() {
457 unknown.dedup();
458 warnings.push(format!(
459 "{WHO}: removed {} row{} comparing groups not on the x axis ({})",
460 unknown.len(),
461 if unknown.len() == 1 { "" } else { "s" },
462 unknown.join(", ")
463 ));
464 }
465 let _ = ns; if rows.is_empty() {
467 return None;
468 }
469
470 let given = |i: usize| {
472 table
473 .column(&self.y_position)
474 .and_then(|c| c.get(i))
475 .and_then(|v| v.as_f64())
476 .filter(|y| y.is_finite())
477 };
478 let max_given = rows
479 .iter()
480 .filter_map(|(i, _)| given(*i))
481 .fold(f64::NEG_INFINITY, f64::max);
482 let (base, step) = match y_range {
483 Some((lo, hi)) => {
484 let span = hi - lo;
485 let unit = if span > 0.0 {
486 span
487 } else if hi != 0.0 {
488 hi.abs()
489 } else {
490 1.0
491 };
492 let step = if self.step_increase.is_finite() && self.step_increase > 0.0 {
493 unit * self.step_increase
494 } else {
495 unit * 0.12
496 };
497 (hi.max(max_given), step)
498 }
499 None if max_given.is_finite() => (max_given, max_given.abs().max(1.0) * 0.12),
500 None => (0.0, 1.0),
501 };
502 let needs_auto = rows.iter().any(|(i, _)| given(*i).is_none());
503 if needs_auto && y_range.is_none() && !max_given.is_finite() {
504 warnings.push(format!(
505 "{WHO}: no y_position and no y data to stack above; brackets placed from 0"
506 ));
507 }
508
509 let mut out = DataFrame::new();
510 let (mut xmin, mut xmax, mut y, mut label, mut pv, mut series) =
511 (vec![], vec![], vec![], vec![], vec![], vec![]);
512 let mut auto_k = 0usize;
513 for (i, p) in rows {
514 xmin.push(g1[i].clone());
515 xmax.push(g2[i].clone());
516 let yy = given(i).unwrap_or_else(|| {
517 auto_k += 1;
518 base + step * auto_k as f64
519 });
520 y.push(Value::Float(yy));
521 label.push(Value::Str(self.label_for(table, i, p)));
522 pv.push(if p.is_finite() {
523 Value::Float(p)
524 } else {
525 Value::Na
526 });
527 series.push(
528 table
529 .column("test_id")
530 .and_then(|c| c.get(i))
531 .cloned()
532 .unwrap_or(Value::Na),
533 );
534 }
535 out.add_column("xmin".into(), xmin);
536 out.add_column("xmax".into(), xmax);
537 out.add_column("y".into(), y);
538 out.add_column("label".into(), label);
539 out.add_column(BRACKET_P_COL.into(), pv);
540 out.add_column(BRACKET_SERIES_COL.into(), series);
541 Some(out)
542 }
543
544 fn label_for(&self, table: &DataFrame, i: usize, p: f64) -> String {
545 let template = match &self.label {
546 Some(t) => t.clone(),
547 None => match table.column("label").and_then(|c| c.get(i)) {
548 Some(v) if !v.is_na() => return v.to_group_key(),
549 _ => "p = {p}".to_string(),
550 },
551 };
552 let mut out = String::with_capacity(template.len());
553 let mut rest = template.as_str();
554 while let Some(open) = rest.find('{') {
555 out.push_str(&rest[..open]);
556 let after = &rest[open + 1..];
557 let Some(close) = after.find('}') else {
558 out.push_str(&rest[open..]);
559 rest = "";
560 break;
561 };
562 let key = &after[..close];
563 let fmt_p = |p: f64| {
564 if p.is_finite() {
565 format_p_number(p)
566 } else {
567 "NA".to_string()
568 }
569 };
570 let sub = match key {
571 "p" => Some(fmt_p(p)),
572 "p.signif" | "stars" => Some(if p.is_finite() {
573 self.signif(p)
574 } else {
575 "NA".to_string()
576 }),
577 "p.format" => Some(if p.is_finite() {
578 format!("p = {}", format_p_number(p))
579 } else {
580 "p = NA".to_string()
581 }),
582 col => table.column(col).and_then(|c| c.get(i)).map(|v| match v {
583 Value::Na => "NA".to_string(),
584 v if col.starts_with('p') && v.as_f64().is_some() && !v.is_datetime() => {
585 fmt_p(v.as_f64().unwrap_or(f64::NAN))
586 }
587 v => crate::format::format_value(v),
588 }),
589 };
590 match sub {
591 Some(s) => out.push_str(&s),
592 None => {
593 out.push('{');
594 out.push_str(key);
595 out.push('}');
596 }
597 }
598 rest = &after[close + 1..];
599 }
600 out.push_str(rest);
601 out
602 }
603}
604
605pub fn format_p_number(p: f64) -> String {
608 if !p.is_finite() {
609 return "NA".to_string();
610 }
611 if p < 2.2e-16 {
612 return "< 2.2e-16".to_string();
613 }
614 if p < 1e-4 {
615 return format!("{p:.2e}");
616 }
617 let digits = (4 - 1 - p.abs().log10().floor() as i32).clamp(0, 12) as usize;
618 let s = format!("{p:.digits$}");
619 if s.contains('.') {
620 s.trim_end_matches('0').trim_end_matches('.').to_string()
621 } else {
622 s
623 }
624}
625
626#[cfg(test)]
627mod table_tests {
628 use super::*;
629
630 fn s(v: &str) -> Value {
631 Value::Str(v.into())
632 }
633
634 fn table() -> DataFrame {
635 let mut t = DataFrame::new();
636 t.add_column("group1".into(), vec![s("a"), s("a"), s("b"), Value::Na]);
637 t.add_column("group2".into(), vec![s("b"), s("c"), s("c"), s("c")]);
638 t.add_column(
639 "p_value".into(),
640 vec![
641 Value::Float(0.0004),
642 Value::Float(0.03),
643 Value::Float(0.4),
644 Value::Float(0.01),
645 ],
646 );
647 t.add_column(
648 "p_adj".into(),
649 vec![
650 Value::Float(0.0012),
651 Value::Na,
652 Value::Float(0.9),
653 Value::Na,
654 ],
655 );
656 t
657 }
658
659 fn levels() -> Vec<String> {
660 vec!["a".into(), "b".into(), "c".into()]
661 }
662
663 #[test]
664 fn p_adj_falls_back_to_p_value_and_stacks() {
665 let mut w = Vec::new();
666 let out = BracketTable::new()
667 .label("{p} {stars}")
668 .resolve(&table(), &levels(), Some((0.0, 10.0)), &mut w)
669 .unwrap();
670 let labels: Vec<String> = out
671 .column("label")
672 .unwrap()
673 .iter()
674 .map(|v| v.to_group_key())
675 .collect();
676 assert_eq!(labels, vec!["0.0012 **", "0.03 *", "0.9 ns"]);
677 let ys: Vec<f64> = out
678 .column("y")
679 .unwrap()
680 .iter()
681 .map(|v| v.as_f64().unwrap())
682 .collect();
683 assert!(
684 (ys[0] - 11.2).abs() < 1e-9
685 && (ys[1] - 12.4).abs() < 1e-9
686 && (ys[2] - 13.6).abs() < 1e-9
687 );
688 assert!(w.iter().any(|m| m.contains("missing group")), "{w:?}");
689 }
690
691 #[test]
692 fn hide_ns_and_unknown_groups() {
693 let mut t = table();
694 t.add_column("y_position".into(), vec![Value::Float(20.0); 4]);
695 let mut w = Vec::new();
696 let out = BracketTable::new()
697 .hide_ns(true)
698 .resolve(&t, &["a".into(), "b".into()], Some((0.0, 1.0)), &mut w)
699 .unwrap();
700 assert_eq!(out.nrows(), 1);
702 assert_eq!(out.column("y").unwrap()[0].as_f64(), Some(20.0));
703 assert!(w.iter().any(|m| m.contains("not on the x axis")), "{w:?}");
704 }
705
706 #[test]
707 fn label_column_and_unknown_keys() {
708 let mut t = table();
709 t.add_column("label".into(), vec![s("custom"), Value::Na, s("x"), s("y")]);
710 let mut w = Vec::new();
711 let out = BracketTable::new().resolve(&t, &[], None, &mut w).unwrap();
712 let labels: Vec<String> = out
713 .column("label")
714 .unwrap()
715 .iter()
716 .map(|v| v.to_group_key())
717 .collect();
718 assert_eq!(labels[0], "custom");
719 assert_eq!(labels[1], "p = 0.03");
720 let mut w = Vec::new();
721 let out = BracketTable::new()
722 .label("{nope} {group1}")
723 .resolve(&t, &[], None, &mut w)
724 .unwrap();
725 assert_eq!(out.column("label").unwrap()[0].to_group_key(), "{nope} a");
726 }
727
728 #[test]
729 fn formats_p_numbers() {
730 assert_eq!(format_p_number(0.03), "0.03");
731 assert_eq!(format_p_number(0.012345), "0.01235");
732 assert_eq!(format_p_number(0.5), "0.5");
733 assert_eq!(format_p_number(1.0), "1");
734 assert_eq!(format_p_number(3e-5), "3.00e-5");
735 assert_eq!(format_p_number(1e-20), "< 2.2e-16");
736 assert_eq!(format_p_number(f64::NAN), "NA");
737 }
738}