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