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