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