1use crate::geom::arrow::arrow;
18use crate::graph_layout::{GraphLayout, PlacedNode};
19use crate::prelude::*;
20use crate::render::backend::{LineEnd, Linetype};
21use crate::scale::linewidth::ScaleLinewidthContinuous;
22
23type Rgb = (u8, u8, u8);
24
25const LABEL_PX: f64 = 13.0;
27const VALUE_PX: f64 = 12.0;
28const BADGE_PX: f64 = 11.0;
29const SMALL_PX: f64 = 11.0;
31const LINE_H: f64 = 16.0;
32const BOX_PAD_X: f64 = 12.0;
33const BOX_PAD_Y: f64 = 9.0;
34const BOX_MIN_W: f64 = 92.0;
35const BOX_MAX_W: f64 = 208.0;
36const SPARK_H: f64 = 22.0;
38const ARROW: f64 = 7.0;
41const MAX_LINES: usize = 3;
43
44fn text_w(s: &str, px: f64, bold: bool) -> f64 {
46 let per = if bold { 0.6 } else { 0.56 };
47 s.chars().count() as f64 * px * per
48}
49
50pub fn edge_label_width(label: &str) -> f64 {
53 label
54 .split('\n')
55 .map(|l| text_w(l, SMALL_PX, false))
56 .fold(0.0, f64::max)
57}
58
59fn wrap(s: &str, max: f64) -> Vec<String> {
65 let cap = ((max / (LABEL_PX * 0.6)).floor() as usize).max(4);
66 let mut pieces: Vec<(String, bool)> = Vec::new();
68 for word in s.split_whitespace() {
69 let chars: Vec<char> = word.chars().collect();
70 let mut start = 0;
71 let mut first = true;
72 while chars.len() - start > cap {
73 let window = &chars[start..start + cap];
74 let cut = window
75 .iter()
76 .rposition(|c| matches!(c, '/' | '-' | '_' | '.' | ','))
77 .filter(|&i| i + 1 >= cap / 3)
78 .map(|i| i + 1)
79 .unwrap_or(cap);
80 pieces.push((chars[start..start + cut].iter().collect(), !first));
81 first = false;
82 start += cut;
83 }
84 pieces.push((chars[start..].iter().collect(), !first));
85 }
86 let mut lines: Vec<String> = Vec::new();
87 let mut cur = String::new();
88 for (piece, glued) in pieces {
89 let sep = if glued || cur.is_empty() { 0 } else { 1 };
90 if !cur.is_empty() && cur.chars().count() + sep + piece.chars().count() > cap {
91 lines.push(std::mem::take(&mut cur));
92 } else if sep == 1 {
93 cur.push(' ');
94 }
95 cur.push_str(&piece);
96 }
97 if !cur.is_empty() {
98 lines.push(cur);
99 }
100 if lines.is_empty() {
101 lines.push(String::new());
102 }
103 if lines.len() > MAX_LINES {
104 let rest = lines[MAX_LINES - 1..].join(" ");
105 let mut last: String = rest.chars().take(cap.saturating_sub(1)).collect();
106 last = last.trim_end().to_string();
107 last.push('…');
108 lines.truncate(MAX_LINES - 1);
109 lines.push(last);
110 }
111 lines
112}
113
114#[derive(Clone, Debug, PartialEq)]
116pub struct NodeBox {
117 pub w: f64,
118 pub h: f64,
119 pub lines: Vec<String>,
120}
121
122pub fn node_box(label: &str, value: Option<&str>, badge: Option<&str>, spark: bool) -> NodeBox {
126 let lines = wrap(label, BOX_MAX_W - 2.0 * BOX_PAD_X);
127 let mut w = lines
128 .iter()
129 .map(|l| text_w(l, LABEL_PX, true))
130 .fold(0.0, f64::max);
131 let mut h = 2.0 * BOX_PAD_Y + LINE_H * lines.len() as f64;
132 if let Some(v) = value {
133 w = w.max(text_w(v, VALUE_PX, true));
134 h += LINE_H;
135 }
136 if let Some(b) = badge {
137 w = w.max(text_w(b, BADGE_PX, false) + 22.0);
138 h += 20.0;
139 }
140 if spark {
141 w = w.max(110.0);
142 h += SPARK_H;
143 }
144 NodeBox {
145 w: (w + 2.0 * BOX_PAD_X).clamp(BOX_MIN_W, BOX_MAX_W),
146 h,
147 lines,
148 }
149}
150
151#[derive(Clone, Debug)]
153pub struct GraphStyle {
154 pub card: Rgb,
156 pub band: Rgb,
158 pub muted: Rgb,
160 pub heading: Rgb,
162 pub ink: Rgb,
164 pub variable_fill: Rgb,
166 pub observed_fill: Rgb,
169 pub plate: Rgb,
171 pub class_prefix: String,
181 pub math_font: Option<String>,
186 pub glyph_fill: Option<Rgb>,
188 pub glyph_ink: Option<Rgb>,
190 pub moved: Option<Rgb>,
196}
197
198impl Default for GraphStyle {
199 fn default() -> Self {
200 GraphStyle {
201 card: (255, 255, 255),
202 band: (226, 228, 233),
203 muted: (107, 114, 128),
204 heading: (17, 24, 39),
205 ink: (31, 41, 55),
206 variable_fill: (229, 231, 235),
207 observed_fill: (75, 85, 99),
208 plate: (107, 114, 128),
209 class_prefix: "gg-graph-".to_string(),
210 math_font: None,
211 glyph_fill: None,
212 glyph_ink: None,
213 moved: None,
214 }
215 }
216}
217
218#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub enum NodeShape {
224 #[default]
226 Box,
227 Circle,
228 FilledCircle,
229 Square,
231 FilledSquare,
233 Text,
235 Glyph,
238 Terminal,
241 Rect,
244 Diamond,
247 DoubleBox,
250}
251
252impl NodeShape {
253 fn name(self) -> &'static str {
254 match self {
255 NodeShape::Box => "box",
256 NodeShape::Circle => "circle",
257 NodeShape::FilledCircle => "filled-circle",
258 NodeShape::Square => "square",
259 NodeShape::FilledSquare => "filled-square",
260 NodeShape::Text => "text",
261 NodeShape::Glyph => "glyph",
262 NodeShape::Terminal => "terminal",
263 NodeShape::Rect => "rect",
264 NodeShape::Diamond => "diamond",
265 NodeShape::DoubleBox => "double-box",
266 }
267 }
268
269 pub fn boxed(self) -> bool {
272 matches!(
273 self,
274 NodeShape::Box | NodeShape::Rect | NodeShape::DoubleBox
275 )
276 }
277}
278
279pub const BELIEF_W: f64 = 46.0;
281pub const BELIEF_H: f64 = 16.0;
282const SQUARE: f64 = 14.0;
284const TERMINAL: f64 = 11.0;
286const GLYPH_SIDE: f64 = 34.0;
288const GLYPH_PX: f64 = 15.0;
289
290const STATE_H: f64 = 15.0;
292const STATE_BAR_W: f64 = 64.0;
293const STATE_NAME_MAX: f64 = 84.0;
294const STATE_GAP: f64 = 6.0;
296const STATE_TEXT_W: f64 = 30.0;
297const STATES_MAX_W: f64 = 224.0;
299const STATE_DELTA_W: f64 = 28.0;
301const MIN_DELTA: f64 = 0.005;
303
304pub fn js_distance(p: &[f64], q: &[f64]) -> f64 {
308 let clean = |v: &[f64]| -> Option<Vec<f64>> {
309 let v: Vec<f64> = v
310 .iter()
311 .map(|x| if x.is_finite() { x.max(0.0) } else { 0.0 })
312 .collect();
313 let s: f64 = v.iter().sum();
314 (s > 0.0).then(|| v.into_iter().map(|x| x / s).collect())
315 };
316 let (Some(p), Some(q)) = (clean(p), clean(q)) else {
317 return 0.0;
318 };
319 if p.len() != q.len() {
320 return 0.0;
321 }
322 let kl = |a: &[f64], m: &[f64]| -> f64 {
323 a.iter()
324 .zip(m)
325 .filter(|(x, _)| **x > 0.0)
326 .map(|(x, y)| x * (x / y).log2())
327 .sum()
328 };
329 let m: Vec<f64> = p.iter().zip(&q).map(|(a, b)| (a + b) / 2.0).collect();
330 let jsd = (kl(&p, &m) + kl(&q, &m)) / 2.0;
331 jsd.clamp(0.0, 1.0).sqrt()
332}
333
334fn mix(a: Rgb, b: Rgb, t: f64) -> Rgb {
336 let t = t.clamp(0.0, 1.0);
337 let m = |x: u8, y: u8| (x as f64 + (y as f64 - x as f64) * t).round() as u8;
338 (m(a.0, b.0), m(a.1, b.1), m(a.2, b.2))
339}
340
341fn moved_share(states: &[StateBar]) -> Option<f64> {
344 let was: Option<Vec<f64>> = states.iter().map(|r| r.was).collect();
345 let was = was?;
346 let now: Vec<f64> = states.iter().map(|r| r.p).collect();
347 let d = js_distance(&now, &was);
348 (d >= 0.01).then(|| (d / 0.4).min(1.0) * 0.45)
349}
350
351fn delta_text(p: f64, was: f64) -> Option<(String, bool)> {
354 let d = p - was;
355 if !d.is_finite() || d.abs() < MIN_DELTA {
356 return None;
357 }
358 let pts = (d.abs() * 100.0).round().max(1.0);
359 Some((
360 format!("{}{pts:.0}", if d > 0.0 { '▲' } else { '▼' }),
361 d > 0.0,
362 ))
363}
364
365const HAND_RECTS: [(f64, f64, f64, f64); 5] = [
369 (0.6, 5.2, 9.2, 11.8),
370 (0.6, 1.8, 2.5, 7.0),
371 (2.8, 0.4, 4.7, 7.0),
372 (5.0, 0.8, 6.9, 7.0),
373 (7.2, 2.2, 9.1, 7.0),
374];
375const HAND_THUMB: [(f64, f64); 4] = [(8.2, 8.4), (11.0, 5.2), (12.2, 6.2), (9.4, 10.6)];
376
377fn state_name(name: &str) -> String {
380 let cap = (STATE_NAME_MAX / (SMALL_PX * 0.56)).floor() as usize;
381 if name.chars().count() <= cap {
382 return name.to_string();
383 }
384 let mut s: String = name.chars().take(cap.saturating_sub(1)).collect();
385 s = s.trim_end().to_string();
386 s.push('…');
387 s
388}
389
390pub fn states_box(
395 label: &str,
396 value: Option<&str>,
397 badge: Option<&str>,
398 states: &[String],
399) -> NodeBox {
400 states_box_with_deltas(label, value, badge, states, false)
401}
402
403pub fn states_box_with_deltas(
406 label: &str,
407 value: Option<&str>,
408 badge: Option<&str>,
409 states: &[String],
410 deltas: bool,
411) -> NodeBox {
412 let b = node_box(label, value, badge, false);
413 if states.is_empty() {
414 return b;
415 }
416 let names = states
417 .iter()
418 .map(|n| text_w(&state_name(n), SMALL_PX, true))
419 .fold(0.0, f64::max);
420 let delta = if deltas { STATE_DELTA_W } else { 0.0 };
421 let rows = names + STATE_GAP + STATE_BAR_W + STATE_GAP + STATE_TEXT_W + delta;
422 NodeBox {
423 w: b.w.max(rows + 2.0 * BOX_PAD_X).min(STATES_MAX_W + delta),
424 h: b.h + 4.0 + STATE_H * states.len() as f64,
425 lines: b.lines,
426 }
427}
428
429pub fn diamond_box(label: &str, value: Option<&str>) -> NodeBox {
432 let lines = wrap(label, 132.0);
433 let mut w = lines
434 .iter()
435 .map(|l| text_w(l, LABEL_PX, true))
436 .fold(0.0, f64::max);
437 let mut h = LINE_H * lines.len() as f64;
438 if let Some(v) = value {
439 w = w.max(text_w(v, VALUE_PX, true));
440 h += LINE_H;
441 }
442 NodeBox {
444 w: (2.0 * w + 16.0).max(72.0),
445 h: (2.0 * h + 8.0).max(44.0),
446 lines,
447 }
448}
449
450const TABLE_NAME_MAX: f64 = 96.0;
452const TABLE_CELL_MAX: f64 = 84.0;
453const TABLE_GAP: f64 = 10.0;
455
456#[derive(Clone, Debug, Default, PartialEq)]
462pub struct NodeTable {
463 pub header: Vec<String>,
466 pub rows: Vec<Vec<String>>,
468 pub marked: Vec<Option<usize>>,
471 pub current: Option<usize>,
474 pub keys: Vec<String>,
477}
478
479fn fit_text(s: &str, max: f64) -> String {
481 let cap = (max / (SMALL_PX * 0.6)).floor() as usize;
482 if s.chars().count() <= cap {
483 return s.to_string();
484 }
485 let mut out: String = s.chars().take(cap.saturating_sub(1)).collect();
486 out = out.trim_end().to_string();
487 out.push('…');
488 out
489}
490
491impl NodeTable {
492 fn has_header(&self) -> bool {
493 self.header.iter().any(|h| !h.is_empty())
494 }
495
496 fn columns(&self) -> usize {
497 self.rows
498 .iter()
499 .map(Vec::len)
500 .chain([self.header.len()])
501 .max()
502 .unwrap_or(0)
503 }
504
505 fn key(&self, c: usize) -> Option<String> {
507 self.keys.get(c).filter(|k| !k.is_empty()).cloned()
508 }
509
510 fn cell(&self, c: usize, s: &str) -> String {
512 fit_text(
513 s,
514 if c == 0 {
515 TABLE_NAME_MAX
516 } else {
517 TABLE_CELL_MAX
518 },
519 )
520 }
521
522 fn widths(&self) -> Vec<f64> {
525 (0..self.columns())
526 .map(|c| {
527 self.rows
528 .iter()
529 .filter_map(|r| r.get(c))
530 .chain(self.header.get(c))
531 .map(|s| text_w(&self.cell(c, s), SMALL_PX, true))
532 .fold(0.0, f64::max)
533 })
534 .collect()
535 }
536
537 fn width(&self) -> f64 {
539 let w = self.widths();
540 w.iter().sum::<f64>() + TABLE_GAP * w.len().saturating_sub(1) as f64
541 }
542}
543
544pub fn table_box(
548 label: &str,
549 value: Option<&str>,
550 badge: Option<&str>,
551 table: &NodeTable,
552) -> NodeBox {
553 let b = node_box(label, value, badge, false);
554 if table.rows.is_empty() {
555 return b;
556 }
557 let rows = table.rows.len() + usize::from(table.has_header());
558 NodeBox {
559 w: b.w.max(table.width() + 2.0 * BOX_PAD_X),
560 h: b.h + 4.0 + STATE_H * rows as f64,
561 lines: b.lines,
562 }
563}
564
565pub fn node_size(shape: NodeShape, label: &str) -> NodeBox {
569 let one = || vec![label.to_string()];
570 match shape {
571 NodeShape::Box | NodeShape::Rect | NodeShape::DoubleBox => {
572 node_box(label, None, None, false)
573 }
574 NodeShape::Diamond => diamond_box(label, None),
575 NodeShape::Circle | NodeShape::FilledCircle => {
576 let d = (text_w(label, LABEL_PX, true) + 14.0).max(30.0);
577 NodeBox {
578 w: d,
579 h: d,
580 lines: one(),
581 }
582 }
583 NodeShape::Square | NodeShape::FilledSquare => NodeBox {
584 w: SQUARE,
585 h: SQUARE,
586 lines: if label.is_empty() { Vec::new() } else { one() },
587 },
588 NodeShape::Terminal => NodeBox {
589 w: TERMINAL,
590 h: TERMINAL,
591 lines: if label.is_empty() { Vec::new() } else { one() },
592 },
593 NodeShape::Text => NodeBox {
594 w: text_w(label, LABEL_PX, false) + 8.0,
595 h: 20.0,
596 lines: one(),
597 },
598 NodeShape::Glyph => {
599 let side = (text_w(label, GLYPH_PX, true) + 14.0).max(GLYPH_SIDE);
600 NodeBox {
601 w: side,
602 h: GLYPH_SIDE,
603 lines: one(),
604 }
605 }
606 }
607}
608
609#[derive(Clone, Debug, Default)]
612pub struct Plate {
613 pub label: String,
614 pub nodes: Vec<usize>,
615}
616
617pub type DataAttr = (String, Option<String>);
620
621#[derive(Clone, Debug, Default, PartialEq)]
625pub struct StateBar {
626 pub name: String,
627 pub p: f64,
629 pub prior: Option<f64>,
631 pub text: String,
633 pub observed: bool,
635 pub was: Option<f64>,
640}
641
642#[derive(Clone, Copy, Debug, PartialEq, Eq)]
644pub enum NodeIcon {
645 Hand,
647}
648
649#[derive(Clone, Debug, Default)]
652pub struct DrawNode {
653 pub id: String,
655 pub shape: NodeShape,
657 pub lines: Vec<String>,
659 pub value: Option<String>,
661 pub badge: Option<(String, Rgb)>,
663 pub stroke: Rgb,
665 pub accent: Option<Rgb>,
668 pub spark: Option<(Vec<f64>, Rgb)>,
670 pub belief: Option<(Vec<f64>, Rgb)>,
673 pub prior: Option<(Vec<f64>, Rgb)>,
677 pub states: Option<(Vec<StateBar>, Rgb)>,
680 pub fill: Option<Rgb>,
683 pub icon: Option<NodeIcon>,
686 pub table: Option<(NodeTable, Rgb)>,
690 pub tooltip: String,
691 pub attrs: Vec<DataAttr>,
694}
695
696#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
698pub enum EdgeLine {
699 #[default]
700 Solid,
701 Dashed,
702 Dots,
704}
705
706#[derive(Clone, Debug, Default)]
710pub struct DrawEdge {
711 pub colour: Rgb,
712 pub width: f64,
714 pub line: EdgeLine,
715 pub class: Option<String>,
717 pub tooltip: String,
718 pub label: Option<String>,
720 pub label_at: Option<f64>,
724 pub undirected: bool,
726 pub label_math: bool,
730 pub attrs: Vec<DataAttr>,
733 pub label_attrs: Vec<DataAttr>,
735 pub cut: bool,
739}
740
741pub fn flow_width(value: Option<f64>, max: f64, line: EdgeLine) -> f64 {
745 let width = match value {
746 Some(v) if max > 0.0 => 1.4 + 5.6 * (v.max(0.0) / max).sqrt(),
747 _ => 1.6,
748 };
749 let width = match line {
750 EdgeLine::Dots => width.clamp(3.0, 6.0),
751 _ => width,
752 };
753 (width * 10.0).round() / 10.0
754}
755
756#[derive(Default)]
758struct Frame(Vec<(String, Vec<Value>)>);
759
760impl Frame {
761 fn col(&mut self, name: &str) -> &mut Vec<Value> {
762 let i = match self.0.iter().position(|(n, _)| n == name) {
763 Some(i) => i,
764 None => {
765 self.0.push((name.to_string(), Vec::new()));
766 self.0.len() - 1
767 }
768 };
769 &mut self.0[i].1
770 }
771 fn num(&mut self, name: &str, v: f64) -> &mut Self {
772 self.col(name).push(Value::Float(v));
773 self
774 }
775 fn txt(&mut self, name: &str, v: impl Into<String>) -> &mut Self {
776 self.col(name).push(Value::Str(v.into()));
777 self
778 }
779 fn opt(&mut self, name: &str, v: Option<String>) -> &mut Self {
780 self.col(name).push(v.map_or(Value::Na, Value::Str));
781 self
782 }
783 fn attrs(&mut self, attrs: &[DataAttr]) -> &mut Self {
785 for (n, v) in attrs {
786 self.opt(&format!("a:{n}"), v.clone());
787 }
788 self
789 }
790 fn is_empty(&self) -> bool {
791 self.0.first().is_none_or(|(_, v)| v.is_empty())
792 }
793 fn attr_aes(&self, mut aes: Aes) -> Aes {
795 for (n, _) in &self.0 {
796 if let Some(name) = n.strip_prefix("a:") {
797 aes = aes.data_attr(name, n);
798 }
799 }
800 aes
801 }
802 fn take(&mut self, h: f64) -> Vec<(String, Vec<Value>)> {
806 let flip = |v: Vec<Value>| -> Vec<Value> {
807 v.into_iter()
808 .map(|x| match x {
809 Value::Float(y) => Value::Float(h - y),
810 other => other,
811 })
812 .collect()
813 };
814 std::mem::take(&mut self.0)
815 .into_iter()
816 .map(|(n, v)| match n.as_str() {
817 "y" => (n, flip(v)),
818 "y0" => ("y1".to_string(), flip(v)),
819 "y1" => ("y0".to_string(), flip(v)),
820 _ => (n, v),
821 })
822 .collect()
823 }
824}
825
826fn by_colour(v: &mut Vec<(Rgb, Frame)>, c: Rgb) -> &mut Frame {
829 let i = match v.iter().position(|(k, _)| *k == c) {
830 Some(i) => i,
831 None => {
832 v.push((c, Frame::default()));
833 v.len() - 1
834 }
835 };
836 &mut v[i].1
837}
838
839fn state_attr(f: &Frame, aes: Aes) -> Aes {
843 if f.0.iter().any(|(n, _)| n == "state") {
844 aes.data_attr("state", "state")
845 } else {
846 aes
847 }
848}
849
850fn hex(c: Rgb) -> String {
851 format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
852}
853
854fn point_at(pts: &[(f64, f64)], t: f64) -> (f64, f64) {
856 let seg = |i: usize| {
857 let (a, b) = (pts[i], pts[i + 1]);
858 ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
859 };
860 let total: f64 = (0..pts.len().saturating_sub(1)).map(seg).sum();
861 let mut left = total * t;
862 for i in 0..pts.len().saturating_sub(1) {
863 let l = seg(i);
864 if l >= left && l > 0.0 {
865 let t = left / l;
866 let (a, b) = (pts[i], pts[i + 1]);
867 return (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
868 }
869 left -= l;
870 }
871 pts.first().copied().unwrap_or((0.0, 0.0))
872}
873
874fn edge_label_at(pts: &[(f64, f64)], label: &str, nodes: &[PlacedNode]) -> (f64, f64) {
878 let lines = label.split('\n').count();
879 let hw = edge_label_width(label) / 2.0 + 3.0;
880 let hh = lines as f64 * 6.6 + 3.0;
881 let clear = |(x, y): (f64, f64)| {
882 let cy = y - 4.0 - 0.36 * SMALL_PX;
883 nodes
884 .iter()
885 .all(|n| (x - n.cx).abs() >= hw + n.w / 2.0 || (cy - n.cy).abs() >= hh + n.h / 2.0)
886 };
887 let mid = point_at(pts, 0.5);
888 [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.18, 0.82]
889 .into_iter()
890 .map(|t| point_at(pts, t))
891 .find(|&p| clear(p))
892 .unwrap_or(mid)
893}
894
895fn end_label_at(pts: &[(f64, f64)], label: &str, t: f64) -> (f64, f64) {
901 use crate::graph_layout::LABEL_CLEAR;
902 let n = pts.len();
903 if n < 2 {
904 return pts.first().copied().unwrap_or((0.0, 0.0));
905 }
906 let (end, prev) = if t >= 0.5 {
907 (pts[n - 1], pts[n - 2])
908 } else {
909 (pts[0], pts[1])
910 };
911 let (dx, dy) = (prev.0 - end.0, prev.1 - end.1);
912 let len = (dx * dx + dy * dy).sqrt();
913 if len == 0.0 {
914 return end;
915 }
916 let (ux, uy) = (dx / len, dy / len);
917 let lines = label.split('\n').count() as f64;
918 let hw = edge_label_width(label) / 2.0;
919 let hh = lines * 6.6;
920 let below_mid = 4.0 + 0.36 * SMALL_PX;
922 if ux.abs() >= uy.abs() {
923 let s = (hw + LABEL_CLEAR).min(len * 0.5);
925 (end.0 + ux * s, end.1 + uy * s)
926 } else {
927 let s = (hh + LABEL_CLEAR).min(len * 0.5);
929 (end.0 + LABEL_CLEAR + hw, end.1 + uy * s + below_mid)
930 }
931}
932
933fn mid_of_baseline(baseline: f64, px: f64) -> f64 {
936 baseline - 0.36 * px
937}
938
939pub fn draw(
946 layout: &GraphLayout,
947 lanes: &[String],
948 plates: &[Plate],
949 nodes: &[DrawNode],
950 edges: &[DrawEdge],
951 style: &GraphStyle,
952 mut theme: Theme,
953) -> GGPlot {
954 let s = style;
955 let class = |name: &str| format!("{}{name}", s.class_prefix);
956 let (w, h) = (layout.w.ceil().max(1.0), layout.h.ceil().max(1.0));
957 theme.legend_position = crate::theme::LegendPosition::None;
958 let mut plot = GGPlot::new(vec![
959 ("x".to_string(), vec![Value::Float(0.0), Value::Float(w)]),
960 ("y".to_string(), vec![Value::Float(0.0), Value::Float(h)]),
961 ])
962 .theme(theme)
963 .scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
966 .scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
967 .coord_cartesian_zoom(Some((0.0, w)), Some((0.0, h)))
968 .scale_color_identity()
969 .scale_fill_identity()
970 .scale_linewidth(
971 ScaleLinewidthContinuous::new()
972 .with_limits(0.0, 16.0)
973 .with_range(0.0, 16.0),
974 )
975 .scale_linetype_manual(vec![
976 ("solid", Linetype::Solid),
977 ("dashed", Linetype::Custom(vec![(6.0, 4.0)])),
978 ("dots", Linetype::Custom(vec![(0.0, 10.0)])),
980 ]);
981 let rect_aes = || Aes::new().xmin("x0").xmax("x1").ymin("y0").ymax("y1");
982 let inert = [("pointer-events", "none")];
983
984 let (mut even, mut odd, mut names) = (Frame::default(), Frame::default(), Frame::default());
986 for &(l, x0, y0, x1, y1) in &layout.bands {
987 let name = lanes.get(l).cloned().unwrap_or_default();
988 let f = if l % 2 == 0 { &mut even } else { &mut odd };
989 f.num("x0", x0).num("x1", x1).num("y0", y0).num("y1", y1);
990 f.txt("lane", name.clone());
991 names
992 .num("x", x0 + 8.0)
993 .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
994 names.txt("label", name);
995 }
996 for (mut f, alpha) in [(even, 0.35), (odd, 0.18)] {
997 if f.is_empty() {
998 continue;
999 }
1000 plot = plot
1001 .geom_rect_with(
1002 GeomRect {
1003 fill: s.band,
1004 alpha,
1005 line_width: 0.0,
1006 ..Default::default()
1007 }
1008 .with_radius(6.0),
1009 )
1010 .layer_data(f.take(h))
1011 .layer_aes(rect_aes().data_attr("lane", "lane"))
1012 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane"))]);
1013 }
1014 if !names.is_empty() {
1015 plot = plot
1016 .geom_text_with(GeomText {
1017 size: SMALL_PX,
1018 color: s.muted,
1019 hjust: 0.0,
1020 fontface: FontFace::Bold,
1021 ..Default::default()
1022 })
1023 .layer_data(names.take(h))
1024 .layer_aes(Aes::new().x("x").y("y").label("label"))
1025 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane-label"))]);
1026 }
1027
1028 let (mut pf, mut pl) = (Frame::default(), Frame::default());
1030 for p in plates {
1031 let members: Vec<&PlacedNode> = p
1032 .nodes
1033 .iter()
1034 .filter_map(|&i| layout.nodes.get(i))
1035 .collect();
1036 if members.is_empty() {
1037 continue;
1038 }
1039 let pad = 8.0;
1040 let x0 = members
1041 .iter()
1042 .map(|n| n.cx - n.w / 2.0)
1043 .fold(f64::INFINITY, f64::min)
1044 - pad;
1045 let x1 = members
1046 .iter()
1047 .map(|n| n.cx + n.w / 2.0)
1048 .fold(f64::NEG_INFINITY, f64::max)
1049 + pad;
1050 let y0 = members
1051 .iter()
1052 .map(|n| n.cy - n.h / 2.0)
1053 .fold(f64::INFINITY, f64::min)
1054 - pad
1055 - 14.0;
1056 let y1 = members
1057 .iter()
1058 .map(|n| n.cy + n.h / 2.0)
1059 .fold(f64::NEG_INFINITY, f64::max)
1060 + pad;
1061 for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] {
1062 pf.num("x", x).num("y", y).txt("lt", "dashed");
1063 pf.txt("g", p.label.clone()).txt("plate", p.label.clone());
1064 }
1065 pl.num("x", x0 + 6.0)
1066 .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
1067 pl.txt("label", p.label.clone());
1068 }
1069 if !pf.is_empty() {
1070 plot = plot
1071 .geom_path_with(GeomPath::default().color(s.plate).linewidth(1.0))
1072 .layer_data(pf.take(h))
1073 .layer_aes(
1074 Aes::new()
1075 .x("x")
1076 .y("y")
1077 .group("g")
1078 .linetype("lt")
1079 .data_attr("plate", "plate"),
1080 )
1081 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate"))]);
1082 plot = plot
1083 .geom_text_with(GeomText {
1084 size: SMALL_PX,
1085 color: s.plate,
1086 hjust: 0.0,
1087 ..Default::default()
1088 })
1089 .layer_data(pl.take(h))
1090 .layer_aes(Aes::new().x("x").y("y").label("label"))
1091 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate-label"))]);
1092 }
1093
1094 let (mut ef, mut uf, mut lf) = (Frame::default(), Frame::default(), Frame::default());
1096 let mut lmf = Frame::default();
1098 let (mut cgap, mut cmark) = (Frame::default(), Frame::default());
1100 for (k, e) in edges.iter().enumerate() {
1101 let Some(route) = layout.edges.get(k) else {
1102 continue;
1103 };
1104 let mut pts = route.clone();
1105 if pts.len() < 2 {
1106 continue;
1107 }
1108 if !e.undirected {
1113 let n = pts.len();
1114 let ((fx, fy), (tx, ty)) = (pts[n - 2], pts[n - 1]);
1115 let len = ((tx - fx).powi(2) + (ty - fy).powi(2)).sqrt().max(1e-6);
1116 let pull = e.width.min(len / 2.0);
1117 pts[n - 1] = (tx - (tx - fx) / len * pull, ty - (ty - fy) / len * pull);
1118 }
1119 if e.cut {
1120 let total: f64 = pts
1121 .windows(2)
1122 .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())
1123 .sum();
1124 if total > 16.0 {
1125 let (mx, my) = point_at(&pts, 0.5);
1126 let (ax, ay) = point_at(&pts, 0.5 - 2.0 / total);
1127 let (bx, by) = point_at(&pts, 0.5 + 2.0 / total);
1128 let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt().max(1e-6);
1129 let (ux, uy) = ((bx - ax) / len, (by - ay) / len);
1130 let g = format!("c{k:04}");
1131 for d in [-4.0, 4.0] {
1132 cgap.num("x", mx + ux * d).num("y", my + uy * d);
1133 cgap.txt("g", g.clone()).num("lw", e.width + 2.5);
1134 cgap.attrs(&e.label_attrs);
1135 }
1136 let (c30, s30) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
1138 let (vx, vy) = (-uy * c30 + ux * s30, ux * c30 + uy * s30);
1139 for (i, off) in [-3.5, 3.5].into_iter().enumerate() {
1140 let (cx, cy) = (mx + ux * off, my + uy * off);
1141 for t in [-5.0, 5.0] {
1142 cmark.num("x", cx + vx * t).num("y", cy + vy * t);
1143 cmark.txt("g", format!("{g}-{i}")).txt("col", hex(e.colour));
1144 cmark.attrs(&e.label_attrs);
1145 }
1146 }
1147 }
1148 }
1149 let ef = if e.undirected { &mut uf } else { &mut ef };
1150 let lt = match e.line {
1151 EdgeLine::Solid => "solid",
1152 EdgeLine::Dashed => "dashed",
1153 EdgeLine::Dots => "dots",
1154 };
1155 for &(x, y) in &pts {
1156 ef.num("x", x).num("y", y).txt("g", format!("e{k:04}"));
1157 ef.txt("col", hex(e.colour))
1158 .num("lw", e.width)
1159 .txt("lt", lt);
1160 ef.opt("cls", e.class.clone()).txt("tip", e.tooltip.clone());
1161 ef.attrs(&e.attrs);
1162 }
1163 let routed = layout.routed.get(k).copied().unwrap_or(false);
1166 if let Some(l) = e.label.as_ref().filter(|_| !routed) {
1167 let (mx, my) = match e.label_at {
1168 Some(t) => end_label_at(route, l, t),
1171 None => edge_label_at(route, l, &layout.nodes),
1172 };
1173 let f = if e.label_math && s.math_font.is_some() {
1174 &mut lmf
1175 } else {
1176 &mut lf
1177 };
1178 f.num("x", mx).num("y", mid_of_baseline(my - 4.0, SMALL_PX));
1179 f.txt("label", l.clone());
1180 f.attrs(&e.label_attrs);
1181 }
1182 }
1183 for (mut f, arrowed) in [(ef, true), (uf, false)] {
1184 if f.is_empty() {
1185 continue;
1186 }
1187 let aes = f.attr_aes(
1188 Aes::new()
1189 .x("x")
1190 .y("y")
1191 .group("g")
1192 .color("col")
1193 .linewidth("lw")
1194 .linetype("lt")
1195 .class("cls")
1196 .tooltip("tip"),
1197 );
1198 let mut geom = GeomPath::default().lineend(LineEnd::Round);
1199 if arrowed {
1200 geom = geom.arrow(
1202 arrow()
1203 .closed()
1204 .angle(29.0)
1205 .length(ARROW + 1.0)
1206 .length_per_linewidth(1.2),
1207 );
1208 }
1209 plot = plot
1210 .geom_path_with(geom)
1211 .layer_data(f.take(h))
1212 .layer_aes(aes)
1213 .layer_svg_attr("class", class("edge"));
1214 }
1215 if !cgap.is_empty() {
1216 let aes = cgap.attr_aes(Aes::new().x("x").y("y").group("g").linewidth("lw"));
1217 plot = plot
1218 .geom_path_with(GeomPath::default().color(s.card).lineend(LineEnd::Butt))
1219 .layer_data(cgap.take(h))
1220 .layer_aes(aes)
1221 .decorative()
1222 .layer_svg_attrs(inert)
1223 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-cut"))]);
1224 let aes = cmark.attr_aes(Aes::new().x("x").y("y").group("g").color("col"));
1225 plot = plot
1226 .geom_path_with(GeomPath::default().linewidth(1.4).lineend(LineEnd::Round))
1227 .layer_data(cmark.take(h))
1228 .layer_aes(aes)
1229 .decorative()
1230 .layer_svg_attrs(inert)
1231 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-cut"))]);
1232 }
1233 if !lmf.is_empty() {
1234 let aes = lmf.attr_aes(Aes::new().x("x").y("y").label("label"));
1235 plot = plot
1236 .geom_text_with(
1237 GeomText {
1238 size: LABEL_PX + 1.0,
1239 color: s.heading,
1240 fontface: FontFace::Italic,
1241 fontfamily: s.math_font.clone().unwrap_or_default(),
1242 ..Default::default()
1243 }
1244 .bg_colour(s.card)
1245 .bg_r(2.0),
1246 )
1247 .layer_data(lmf.take(h))
1248 .layer_aes(aes)
1249 .layer_svg_attrs(inert)
1250 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
1251 }
1252 if !lf.is_empty() {
1253 let aes = lf.attr_aes(Aes::new().x("x").y("y").label("label"));
1255 plot = plot
1256 .geom_text_with(
1257 GeomText {
1258 size: SMALL_PX,
1259 color: s.muted,
1260 ..Default::default()
1261 }
1262 .bg_colour(s.card)
1263 .bg_r(2.0),
1264 )
1265 .layer_data(lf.take(h))
1266 .layer_aes(aes)
1267 .layer_svg_attrs(inert)
1268 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
1269 }
1270
1271 let mut order: Vec<usize> = (0..nodes.len().min(layout.nodes.len())).collect();
1274 order.sort_by_key(|&i| (layout.nodes[i].order, i));
1275 let mut boxes: Vec<((Rgb, NodeShape, Rgb), Frame)> = Vec::new();
1277 let mut outlines: Vec<(Rgb, Frame)> = Vec::new();
1279 let (mut hits, mut diamonds) = (Frame::default(), Vec::<(Rgb, Frame)>::new());
1281 let (mut sprior, mut stick, mut sbar) = (Frame::default(), Frame::default(), Frame::default());
1284 let (mut sname, mut sseen, mut stext) = (Frame::default(), Frame::default(), Frame::default());
1285 let (mut sup, mut sdown) = (Frame::default(), Frame::default());
1287 let (mut tband, mut tmarkbg) = (Frame::default(), Frame::default());
1290 let (mut thead_l, mut thead_r) = (Frame::default(), Frame::default());
1291 let (mut tname, mut tcell, mut tmark) = (Frame::default(), Frame::default(), Frame::default());
1292 let (mut ibadge, mut irect, mut ipoly) = (Frame::default(), Frame::default(), Frame::default());
1294 let mut beliefs = Frame::default();
1295 let mut priors = Frame::default();
1296 let mut shaped: Vec<((NodeShape, u64, Rgb), Frame)> = Vec::new();
1298 let (mut inside, mut inverse, mut above, mut glyphs, mut texts, mut beside) = (
1299 Frame::default(),
1300 Frame::default(),
1301 Frame::default(),
1302 Frame::default(),
1303 Frame::default(),
1304 Frame::default(),
1305 );
1306 let mut badges: Vec<(Rgb, Frame)> = Vec::new();
1307 let (mut accent, mut lines, mut values) =
1308 (Frame::default(), Frame::default(), Frame::default());
1309 let (mut dots, mut btext, mut spark, mut ends) = (
1310 Frame::default(),
1311 Frame::default(),
1312 Frame::default(),
1313 Frame::default(),
1314 );
1315 for v in order {
1316 let nd = &nodes[v];
1317 let pn = &layout.nodes[v];
1318 let id = nd.id.clone();
1319 let (x, y) = (pn.cx - pn.w / 2.0, pn.cy - pn.h / 2.0);
1320 let squared = matches!(nd.shape, NodeShape::Square | NodeShape::FilledSquare);
1322 let base = y - if squared { 17.0 } else { 3.0 };
1323 let x0 = pn.cx - BELIEF_W / 2.0;
1324 let curve = |hs: &[f64]| -> Vec<(f64, f64)> {
1325 let last = (hs.len() - 1) as f64;
1326 hs.iter()
1327 .enumerate()
1328 .map(|(i, &h)| {
1329 (
1330 x0 + BELIEF_W * i as f64 / last,
1331 base - h.clamp(0.0, 1.0) * BELIEF_H,
1332 )
1333 })
1334 .collect()
1335 };
1336 if let Some((hs, col)) = nd.prior.as_ref().filter(|(h, _)| h.len() >= 3) {
1338 for (px, py) in curve(hs) {
1339 priors.num("x", px).num("y", py).txt("g", id.clone());
1340 priors.txt("col", hex(*col)).txt("lt", "dashed");
1341 priors.txt("of", id.clone());
1342 }
1343 }
1344 if let Some((hs, col)) = nd.belief.as_ref().filter(|(h, _)| h.len() >= 3) {
1345 let mut pts = curve(hs);
1346 pts.push((x0 + BELIEF_W, base));
1347 pts.push((x0, base));
1348 for (px, py) in pts {
1349 beliefs.num("x", px).num("y", py).txt("g", id.clone());
1350 beliefs.txt("fill", hex(*col)).txt("of", id.clone());
1351 }
1352 }
1353 if nd.shape == NodeShape::Diamond {
1354 hits.num("x0", x)
1355 .num("x1", x + pn.w)
1356 .num("y0", y)
1357 .num("y1", y + pn.h);
1358 hits.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1359 let f = by_colour(&mut diamonds, nd.stroke);
1360 for (px, py) in [(pn.cx, y), (x + pn.w, pn.cy), (pn.cx, y + pn.h), (x, pn.cy)] {
1361 f.num("x", px).num("y", py).txt("g", id.clone());
1362 f.txt("fill", hex(nd.fill.unwrap_or(s.card)))
1363 .txt("of", id.clone());
1364 }
1365 let n = nd.lines.len() + usize::from(nd.value.is_some());
1367 let mut base = pn.cy - LINE_H * n as f64 / 2.0 + 12.0;
1368 for line in &nd.lines {
1369 lines
1370 .num("x", pn.cx)
1371 .num("y", mid_of_baseline(base, LABEL_PX));
1372 lines.txt("label", line.clone()).txt("of", id.clone());
1373 base += LINE_H;
1374 }
1375 if let Some(fv) = &nd.value {
1376 values
1377 .num("x", pn.cx)
1378 .num("y", mid_of_baseline(base, VALUE_PX));
1379 values.txt("label", fv.clone()).txt("of", id.clone());
1380 }
1381 continue;
1382 }
1383 if !nd.shape.boxed() {
1384 let r = match nd.shape {
1385 NodeShape::Circle | NodeShape::FilledCircle => pn.w.min(pn.h) / 2.0,
1386 NodeShape::Square | NodeShape::FilledSquare | NodeShape::Terminal => 1.5,
1387 NodeShape::Glyph => 4.0,
1388 _ => 0.0,
1389 };
1390 let (fill, stroke) = match nd.shape {
1391 NodeShape::Circle => (s.variable_fill, nd.stroke),
1392 NodeShape::FilledCircle | NodeShape::FilledSquare | NodeShape::Terminal => {
1395 let c = nd.accent.unwrap_or(s.observed_fill);
1396 (c, c)
1397 }
1398 NodeShape::Square => (s.card, nd.stroke),
1399 NodeShape::Glyph => (s.glyph_fill.unwrap_or(s.card), nd.stroke),
1400 _ => (s.card, s.card),
1401 };
1402 let key = (nd.shape, r.to_bits(), stroke);
1403 let i = match shaped.iter().position(|(k, _)| *k == key) {
1404 Some(i) => i,
1405 None => {
1406 shaped.push((key, Frame::default()));
1407 shaped.len() - 1
1408 }
1409 };
1410 let f = &mut shaped[i].1;
1411 f.num("x0", x)
1412 .num("x1", x + pn.w)
1413 .num("y0", y)
1414 .num("y1", y + pn.h);
1415 f.txt("fill", hex(fill));
1416 f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1417 let label = nd.lines.join(" ");
1418 if label.is_empty() {
1419 continue;
1420 }
1421 let target = match nd.shape {
1422 NodeShape::Glyph => &mut glyphs,
1423 NodeShape::FilledCircle => &mut inverse,
1424 NodeShape::Square | NodeShape::FilledSquare => &mut above,
1425 NodeShape::Text => &mut texts,
1427 NodeShape::Terminal => &mut beside,
1428 _ => &mut inside,
1429 };
1430 let ly = match nd.shape {
1431 NodeShape::Square | NodeShape::FilledSquare => y - 4.0 - 0.36 * SMALL_PX,
1432 _ => pn.cy,
1433 };
1434 let lx = match nd.shape {
1436 NodeShape::Terminal => x + pn.w + 5.0,
1437 _ => pn.cx,
1438 };
1439 target.num("x", lx).num("y", ly);
1440 target.txt("label", label).txt("of", id.clone());
1441 continue;
1442 }
1443 let fill = nd.fill.unwrap_or_else(|| {
1445 match (
1446 s.moved,
1447 nd.states.as_ref().and_then(|(r, _)| moved_share(r)),
1448 ) {
1449 (Some(c), Some(t)) => mix(s.card, c, t),
1450 _ => s.card,
1451 }
1452 });
1453 let key = (nd.stroke, nd.shape, fill);
1454 let i = match boxes.iter().position(|(k, _)| *k == key) {
1455 Some(i) => i,
1456 None => {
1457 boxes.push((key, Frame::default()));
1458 boxes.len() - 1
1459 }
1460 };
1461 let f = &mut boxes[i].1;
1462 if nd.shape == NodeShape::DoubleBox {
1463 let o = by_colour(&mut outlines, nd.stroke);
1464 o.num("x0", x + 3.5)
1465 .num("x1", x + pn.w - 3.5)
1466 .num("y0", y + 3.5)
1467 .num("y1", y + pn.h - 3.5);
1468 o.txt("of", id.clone());
1469 }
1470 f.num("x0", x)
1471 .num("x1", x + pn.w)
1472 .num("y0", y)
1473 .num("y1", y + pn.h);
1474 f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1475 if let Some(NodeIcon::Hand) = nd.icon {
1477 let (bx, by) = (x + pn.w - 11.0, y - 7.0);
1478 ibadge
1479 .num("x0", bx)
1480 .num("x1", bx + 18.0)
1481 .num("y0", by)
1482 .num("y1", by + 18.0);
1483 ibadge.txt("of", id.clone());
1484 let (ox, oy) = (bx + 3.0, by + 3.0);
1485 for (x0, y0, x1, y1) in HAND_RECTS {
1486 irect
1487 .num("x0", ox + x0)
1488 .num("x1", ox + x1)
1489 .num("y0", oy + y0)
1490 .num("y1", oy + y1);
1491 irect.txt("of", id.clone());
1492 }
1493 for (px, py) in HAND_THUMB {
1494 ipoly.num("x", ox + px).num("y", oy + py);
1495 ipoly.txt("g", id.clone()).txt("of", id.clone());
1496 }
1497 }
1498
1499 if let Some(a) = nd.accent {
1500 accent.num("x0", x + 1.5).num("x1", x + 4.5);
1501 accent
1502 .num("y0", y + 6.0)
1503 .num("y1", y + 6.0 + (pn.h - 12.0).max(4.0));
1504 accent.txt("fill", hex(a)).txt("of", id.clone());
1505 }
1506 let mut base = y + BOX_PAD_Y + 12.0;
1507 for line in &nd.lines {
1508 lines
1509 .num("x", pn.cx)
1510 .num("y", mid_of_baseline(base, LABEL_PX));
1511 lines.txt("label", line.clone()).txt("of", id.clone());
1512 base += LINE_H;
1513 }
1514 if let Some(fv) = &nd.value {
1515 values
1516 .num("x", pn.cx)
1517 .num("y", mid_of_baseline(base, VALUE_PX));
1518 values.txt("label", fv.clone()).txt("of", id.clone());
1519 base += LINE_H;
1520 }
1521 if let Some((b, dot)) = &nd.badge {
1522 let bw = text_w(b, BADGE_PX, false) + 20.0;
1523 let (bx, by) = (pn.cx - bw / 2.0, base - 9.0);
1524 let f = by_colour(&mut badges, *dot);
1525 f.num("x0", bx)
1526 .num("x1", bx + bw)
1527 .num("y0", by)
1528 .num("y1", by + 16.0);
1529 f.txt("of", id.clone());
1530 dots.num("x", bx + 9.0).num("y", by + 8.0);
1531 dots.txt("col", hex(*dot)).txt("of", id.clone());
1532 btext.num("x", bx + 15.0).num("y", by + 8.0);
1533 btext.txt("label", b.clone()).txt("of", id.clone());
1534 base += 20.0;
1535 }
1536 if let Some((rows, colour)) = nd.states.as_ref().filter(|(r, _)| !r.is_empty()) {
1539 let names = rows
1540 .iter()
1541 .map(|r| text_w(&state_name(&r.name), SMALL_PX, true))
1542 .fold(0.0, f64::max);
1543 let bx = x + BOX_PAD_X + names + STATE_GAP;
1544 let delta = if rows.iter().any(|r| r.was.is_some()) {
1545 STATE_DELTA_W
1546 } else {
1547 0.0
1548 };
1549 let bw = (pn.w - 2.0 * BOX_PAD_X - names - 2.0 * STATE_GAP - STATE_TEXT_W - delta)
1551 .clamp(16.0, STATE_BAR_W);
1552 base += 4.0;
1553 for r in rows {
1554 let cy = mid_of_baseline(base, SMALL_PX);
1555 let f = if r.observed { &mut sseen } else { &mut sname };
1556 f.num("x", x + BOX_PAD_X).num("y", cy);
1557 f.txt("label", state_name(&r.name)).txt("of", id.clone());
1558 f.txt("state", r.name.clone());
1559 if let Some(q) = r.prior {
1560 let q = if q.is_finite() {
1561 q.clamp(0.0, 1.0)
1562 } else {
1563 0.0
1564 };
1565 sprior
1566 .num("x0", bx)
1567 .num("x1", bx + bw * q)
1568 .num("y0", cy - 5.0)
1569 .num("y1", cy + 5.0);
1570 sprior.txt("fill", hex(s.muted)).txt("of", id.clone());
1571 stick
1572 .num("x0", bx + bw * q - 0.75)
1573 .num("x1", bx + bw * q + 0.75)
1574 .num("y0", cy - 6.0)
1575 .num("y1", cy + 6.0);
1576 stick.txt("fill", hex(s.muted)).txt("of", id.clone());
1577 }
1578 let p = if r.p.is_finite() {
1579 r.p.clamp(0.0, 1.0)
1580 } else {
1581 0.0
1582 };
1583 sbar.num("x0", bx)
1584 .num("x1", bx + bw * p)
1585 .num("y0", cy - 3.5)
1586 .num("y1", cy + 3.5);
1587 sbar.txt("fill", hex(*colour)).txt("of", id.clone());
1588 stext.num("x", bx + bw + STATE_GAP).num("y", cy);
1589 stext.txt("label", r.text.clone()).txt("of", id.clone());
1590 stext.txt("state", r.name.clone());
1591 if let Some((t, up)) = r.was.and_then(|w| delta_text(p, w)) {
1592 let f = if up { &mut sup } else { &mut sdown };
1593 f.num("x", bx + bw + STATE_GAP + STATE_TEXT_W).num("y", cy);
1594 f.txt("label", t).txt("of", id.clone());
1595 }
1596 base += STATE_H;
1597 }
1598 }
1599 if let Some((t, colour)) = nd.table.as_ref().filter(|(t, _)| !t.rows.is_empty()) {
1602 let widths = t.widths();
1603 let x0 = pn.cx - t.width() / 2.0;
1604 let mut edges = Vec::with_capacity(widths.len());
1606 let mut cx = x0;
1607 for w in &widths {
1608 edges.push((cx, cx + w));
1609 cx += w + TABLE_GAP;
1610 }
1611 base += 4.0;
1612 if t.has_header() {
1613 let cy = mid_of_baseline(base, SMALL_PX);
1614 for (c, h) in t.header.iter().enumerate().filter(|(_, h)| !h.is_empty()) {
1615 let (f, hx) = if c == 0 {
1616 (&mut thead_l, edges[c].0)
1617 } else {
1618 (&mut thead_r, edges[c].1)
1619 };
1620 f.num("x", hx).num("y", cy);
1621 f.txt("label", t.cell(c, h)).txt("of", id.clone());
1622 if c > 0 {
1623 f.opt("state", t.key(c));
1624 }
1625 }
1626 base += STATE_H;
1627 }
1628 for (k, row) in t.rows.iter().enumerate() {
1629 let cy = mid_of_baseline(base, SMALL_PX);
1630 if t.current == Some(k) {
1631 tband
1632 .num("x0", x + 4.0)
1633 .num("x1", x + pn.w - 4.0)
1634 .num("y0", cy - 7.0)
1635 .num("y1", cy + 7.0);
1636 tband.txt("fill", hex(s.muted)).txt("of", id.clone());
1637 }
1638 let mark = t.marked.get(k).copied().flatten();
1639 for (c, cell) in row.iter().enumerate().take(edges.len()) {
1640 let marked = c > 0 && mark == Some(c);
1641 if marked {
1642 tmarkbg
1643 .num("x0", edges[c].0 - 3.0)
1644 .num("x1", edges[c].1 + 3.0)
1645 .num("y0", cy - 6.5)
1646 .num("y1", cy + 6.5);
1647 tmarkbg.txt("fill", hex(*colour)).txt("of", id.clone());
1648 }
1649 let (f, cx) = match (c, marked) {
1650 (0, _) => (&mut tname, edges[c].0),
1651 (_, true) => (&mut tmark, edges[c].1),
1652 _ => (&mut tcell, edges[c].1),
1653 };
1654 f.num("x", cx).num("y", cy);
1655 f.txt("label", t.cell(c, cell)).txt("of", id.clone());
1656 if c > 0 {
1657 f.opt("state", t.key(c));
1658 }
1659 }
1660 base += STATE_H;
1661 }
1662 }
1663 if let Some((values, colour)) = nd.spark.as_ref().filter(|(v, _)| v.len() >= 2) {
1665 let (lo, hi) = values
1666 .iter()
1667 .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1668 (a.min(v), b.max(v))
1669 });
1670 let rng = if hi > lo { hi - lo } else { 1.0 };
1671 let (sx0, sw) = (x + BOX_PAD_X, pn.w - 2.0 * BOX_PAD_X);
1672 let (top, sh) = (base - 8.0, SPARK_H - 8.0);
1673 let last = values.len() - 1;
1674 let col = hex(*colour);
1675 for (i, &sv) in values.iter().enumerate() {
1676 let (px, py) = (
1677 sx0 + sw * i as f64 / last as f64,
1678 top + sh - (sv - lo) / rng * sh,
1679 );
1680 spark.num("x", px).num("y", py).txt("g", id.clone());
1681 spark.txt("col", col.clone()).txt("of", id.clone());
1682 if i == last {
1683 ends.num("x", px).num("y", py);
1684 ends.txt("col", col.clone()).txt("of", id.clone());
1685 }
1686 }
1687 }
1688 }
1689 for ((stroke, shape, fill), mut f) in boxes {
1690 let aes = f.attr_aes(rect_aes().tooltip("tip"));
1691 let cls = match shape {
1692 NodeShape::Box => class("node"),
1693 _ => format!(
1694 "{} {}",
1695 class("node"),
1696 class(&format!("node-{}", shape.name()))
1697 ),
1698 };
1699 plot = plot
1700 .geom_rect_with(
1701 GeomRect {
1702 fill,
1703 color: stroke,
1704 alpha: 1.0,
1705 line_width: 1.2,
1706 ..Default::default()
1707 }
1708 .with_radius(if shape == NodeShape::Rect { 0.0 } else { 8.0 }),
1709 )
1710 .layer_data(f.take(h))
1711 .layer_aes(aes)
1712 .layer_svg_attr("class", cls);
1713 }
1714 if !hits.is_empty() {
1715 let aes = hits.attr_aes(rect_aes().tooltip("tip"));
1717 let cls = format!("{} {}", class("node"), class("node-diamond"));
1718 plot = plot
1719 .geom_rect_with(GeomRect {
1720 fill: s.card,
1721 alpha: 0.0,
1722 line_width: 0.0,
1723 ..Default::default()
1724 })
1725 .layer_data(hits.take(h))
1726 .layer_aes(aes)
1727 .layer_svg_attr("class", cls);
1728 }
1729 for ((shape, r, stroke), mut f) in shaped {
1730 let aes = f.attr_aes(rect_aes().fill("fill").tooltip("tip"));
1731 let cls = format!(
1732 "{} {}",
1733 class("node"),
1734 class(&format!("node-{}", shape.name()))
1735 );
1736 plot = plot
1737 .geom_rect_with(
1738 GeomRect {
1739 color: stroke,
1740 alpha: 1.0,
1741 line_width: if shape == NodeShape::Text { 0.0 } else { 1.2 },
1742 ..Default::default()
1743 }
1744 .with_radius(f64::from_bits(r)),
1745 )
1746 .layer_data(f.take(h))
1747 .layer_aes(aes)
1748 .layer_svg_attr("class", cls);
1749 }
1750 if !priors.is_empty() {
1751 plot = plot
1752 .geom_path_with(GeomPath {
1753 alpha: 0.7,
1754 ..GeomPath::default().linewidth(1.0)
1755 })
1756 .layer_data(priors.take(h))
1757 .layer_aes(
1758 Aes::new()
1759 .x("x")
1760 .y("y")
1761 .group("g")
1762 .color("col")
1763 .linetype("lt")
1764 .group_wrap("of", "of"),
1765 )
1766 .decorative()
1767 .layer_svg_attrs(inert)
1768 .layer_svg_attr("class", class("node-prior"));
1769 }
1770 if !beliefs.is_empty() {
1771 plot = plot
1772 .geom_polygon_with(GeomPolygon {
1773 alpha: 0.45,
1774 line_width: 0.0,
1775 ..Default::default()
1776 })
1777 .layer_data(beliefs.take(h))
1778 .layer_aes(
1779 Aes::new()
1780 .x("x")
1781 .y("y")
1782 .group("g")
1783 .fill("fill")
1784 .group_wrap("of", "of"),
1785 )
1786 .decorative()
1787 .layer_svg_attrs(inert)
1788 .layer_svg_attr("class", class("node-belief"));
1789 }
1790 let of = |a: Aes| a.group_wrap("of", "of");
1792 if !accent.is_empty() {
1793 plot = plot
1794 .geom_rect_with(
1795 GeomRect {
1796 alpha: 1.0,
1797 line_width: 0.0,
1798 ..Default::default()
1799 }
1800 .with_radius(1.5),
1801 )
1802 .layer_data(accent.take(h))
1803 .layer_aes(of(rect_aes().fill("fill")))
1804 .decorative()
1805 .layer_svg_attrs(inert);
1806 }
1807 for (stroke, mut f) in outlines {
1808 plot = plot
1809 .geom_rect_with(
1810 GeomRect {
1811 fill: s.card,
1812 color: stroke,
1813 alpha: 0.0,
1814 line_width: 1.0,
1815 ..Default::default()
1816 }
1817 .with_radius(5.5),
1818 )
1819 .layer_data(f.take(h))
1820 .layer_aes(of(rect_aes()))
1821 .decorative()
1822 .layer_svg_attrs(inert)
1823 .layer_svg_attr("class", class("node-outline"));
1824 }
1825 for (stroke, mut f) in diamonds {
1826 plot = plot
1827 .geom_polygon_with(GeomPolygon {
1828 color: stroke,
1829 alpha: 1.0,
1830 line_width: 1.2,
1831 ..Default::default()
1832 })
1833 .layer_data(f.take(h))
1834 .layer_aes(of(Aes::new().x("x").y("y").group("g").fill("fill")))
1835 .decorative()
1836 .layer_svg_attrs(inert)
1837 .layer_svg_attr("class", class("node-diamond-mark"));
1838 }
1839 for (mut f, alpha, cls) in [
1840 (sprior, 0.28, "node-state-prior"),
1841 (sbar, 0.9, "node-state-bar"),
1842 (stick, 0.9, "node-state-prior"),
1843 (tband, 0.14, "node-table-current"),
1844 (tmarkbg, 0.2, "node-table-mark"),
1845 ] {
1846 if f.is_empty() {
1847 continue;
1848 }
1849 plot = plot
1850 .geom_rect_with(GeomRect {
1851 alpha,
1852 line_width: 0.0,
1853 ..Default::default()
1854 })
1855 .layer_data(f.take(h))
1856 .layer_aes(of(rect_aes().fill("fill")))
1857 .decorative()
1858 .layer_svg_attrs(inert)
1859 .layer_svg_attr("class", class(cls));
1860 }
1861 for (mut f, colour, face, cls) in [
1862 (sname, s.ink, FontFace::Plain, "node-state"),
1863 (sseen, s.heading, FontFace::Bold, "node-state"),
1864 (stext, s.muted, FontFace::Plain, "node-state-value"),
1865 ] {
1866 if f.is_empty() {
1867 continue;
1868 }
1869 plot = plot
1870 .geom_text_with(GeomText {
1871 size: SMALL_PX,
1872 color: colour,
1873 fontface: face,
1874 hjust: 0.0,
1875 ..Default::default()
1876 })
1877 .layer_aes(of(state_attr(&f, Aes::new().x("x").y("y").label("label"))))
1878 .layer_data(f.take(h))
1879 .layer_svg_attrs(inert)
1880 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class(cls))]);
1881 }
1882 for (mut f, colour, face, hjust, cls) in [
1883 (thead_l, s.muted, FontFace::Plain, 0.0, "node-table-head"),
1884 (thead_r, s.muted, FontFace::Plain, 1.0, "node-table-head"),
1885 (tname, s.ink, FontFace::Plain, 0.0, "node-table-name"),
1886 (tcell, s.muted, FontFace::Plain, 1.0, "node-table-cell"),
1887 (
1888 tmark,
1889 s.heading,
1890 FontFace::Bold,
1891 1.0,
1892 "node-table-cell node-table-chosen",
1893 ),
1894 ] {
1895 if f.is_empty() {
1896 continue;
1897 }
1898 let cls = cls.split(' ').map(&class).collect::<Vec<_>>().join(" ");
1899 plot = plot
1900 .geom_text_with(GeomText {
1901 size: SMALL_PX,
1902 color: colour,
1903 fontface: face,
1904 hjust,
1905 ..Default::default()
1906 })
1907 .layer_aes(of(state_attr(&f, Aes::new().x("x").y("y").label("label"))))
1908 .layer_data(f.take(h))
1909 .layer_svg_attrs(inert)
1910 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*cls)]);
1911 }
1912 for (mut f, face, colour) in [
1913 (sup, FontFace::Bold, s.heading),
1914 (sdown, FontFace::Plain, s.muted),
1915 ] {
1916 if f.is_empty() {
1917 continue;
1918 }
1919 plot = plot
1920 .geom_text_with(GeomText {
1921 size: SMALL_PX - 1.0,
1922 color: colour,
1923 fontface: face,
1924 hjust: 0.0,
1925 ..Default::default()
1926 })
1927 .layer_data(f.take(h))
1928 .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1929 .layer_svg_attrs(inert)
1930 .layer_svg_attrs([
1931 ("aria-hidden", "true"),
1932 ("class", &*class("node-state-delta")),
1933 ]);
1934 }
1935 if !ibadge.is_empty() {
1936 plot = plot
1937 .geom_rect_with(
1938 GeomRect {
1939 fill: s.card,
1940 color: s.heading,
1941 alpha: 1.0,
1942 line_width: 1.1,
1943 ..Default::default()
1944 }
1945 .with_radius(9.0),
1946 )
1947 .layer_data(ibadge.take(h))
1948 .layer_aes(of(rect_aes()))
1949 .decorative()
1950 .layer_svg_attrs(inert)
1951 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
1952 plot = plot
1953 .geom_rect_with(
1954 GeomRect {
1955 fill: s.heading,
1956 alpha: 1.0,
1957 line_width: 0.0,
1958 ..Default::default()
1959 }
1960 .with_radius(0.9),
1961 )
1962 .layer_data(irect.take(h))
1963 .layer_aes(of(rect_aes()))
1964 .decorative()
1965 .layer_svg_attrs(inert)
1966 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
1967 plot = plot
1968 .geom_polygon_with(GeomPolygon {
1969 fill: s.heading,
1970 alpha: 1.0,
1971 line_width: 0.0,
1972 ..Default::default()
1973 })
1974 .layer_data(ipoly.take(h))
1975 .layer_aes(of(Aes::new().x("x").y("y").group("g")))
1976 .decorative()
1977 .layer_svg_attrs(inert)
1978 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
1979 }
1980 for (mut f, size, colour, cls, math, hjust) in [
1981 (lines, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1982 (values, VALUE_PX, s.ink, class("node-value"), false, 0.5),
1983 (inside, LABEL_PX, s.heading, class("node-label"), true, 0.5),
1984 (texts, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1985 (inverse, LABEL_PX, s.card, class("node-label"), true, 0.5),
1986 (above, SMALL_PX, s.muted, class("node-label"), true, 0.5),
1987 (beside, LABEL_PX, s.heading, class("node-label"), true, 0.0),
1988 (
1989 glyphs,
1990 GLYPH_PX,
1991 s.glyph_ink.unwrap_or(s.heading),
1992 class("node-label"),
1993 true,
1994 0.5,
1995 ),
1996 ] {
1997 if f.is_empty() {
1998 continue;
1999 }
2000 let (fontfamily, fontface, size) = match s.math_font.as_ref().filter(|_| math) {
2002 Some(family) => (family.clone(), FontFace::Italic, size + 2.0),
2003 None => (String::new(), FontFace::Bold, size),
2004 };
2005 plot = plot
2006 .geom_text_with(GeomText {
2007 size,
2008 color: colour,
2009 fontface,
2010 fontfamily,
2011 hjust,
2012 ..Default::default()
2013 })
2014 .layer_data(f.take(h))
2015 .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2016 .layer_svg_attrs(inert)
2017 .layer_svg_attrs([("aria-hidden", "true"), ("class", cls.as_str())]);
2018 }
2019 for (dot, mut f) in badges {
2020 plot = plot
2021 .geom_rect_with(
2022 GeomRect {
2023 fill: s.card,
2024 color: dot,
2025 alpha: 0.0,
2026 line_width: 1.0,
2027 ..Default::default()
2028 }
2029 .with_radius(8.0),
2030 )
2031 .layer_data(f.take(h))
2032 .layer_aes(of(rect_aes()))
2033 .decorative()
2034 .layer_svg_attrs(inert);
2035 }
2036 for (mut f, size) in [(dots, 3.0), (ends, 2.2)] {
2037 if f.is_empty() {
2038 continue;
2039 }
2040 plot = plot
2041 .geom_point_with(GeomPoint {
2042 size,
2043 ..Default::default()
2044 })
2045 .layer_data(f.take(h))
2046 .layer_aes(of(Aes::new().x("x").y("y").color("col")))
2047 .decorative()
2048 .layer_svg_attrs(inert);
2049 }
2050 if !btext.is_empty() {
2051 plot = plot
2052 .geom_text_with(GeomText {
2053 size: BADGE_PX,
2054 color: s.ink,
2055 hjust: 0.0,
2056 ..Default::default()
2057 })
2058 .layer_data(btext.take(h))
2059 .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2060 .layer_svg_attrs(inert)
2061 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-badge"))]);
2062 }
2063 if !spark.is_empty() {
2064 plot = plot
2065 .geom_path_with(GeomPath::default().linewidth(1.4))
2066 .layer_data(spark.take(h))
2067 .layer_aes(of(Aes::new().x("x").y("y").group("g").color("col")))
2068 .decorative()
2069 .layer_svg_attrs(inert)
2070 .layer_svg_attr("class", class("node-spark"));
2071 }
2072 plot
2073}
2074
2075#[cfg(test)]
2076mod tests {
2077 use super::*;
2078 use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
2079
2080 #[test]
2081 fn an_end_label_sits_beside_its_box() {
2082 let hw = edge_label_width("variance") / 2.0;
2085 let (x, y) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "variance", 0.8);
2086 assert!(
2087 (x - (100.0 - hw - crate::graph_layout::LABEL_CLEAR)).abs() < 1e-9 && y == 0.0,
2088 "{x} {y}"
2089 );
2090 let (x, _) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "mean", 0.2);
2091 assert!(
2092 x - edge_label_width("mean") / 2.0 >= crate::graph_layout::LABEL_CLEAR - 1e-9,
2093 "{x}"
2094 );
2095 let (x, y) = end_label_at(&[(50.0, 0.0), (50.0, 40.0)], "out", 0.2);
2097 assert!(
2098 x - edge_label_width("out") / 2.0 > 50.0 && y > 0.0,
2099 "{x} {y}"
2100 );
2101 let (x, _) = end_label_at(&[(0.0, 0.0), (20.0, 0.0)], "variance", 0.8);
2103 assert!((x - 10.0).abs() < 1e-9, "{x}");
2104 }
2105
2106 #[test]
2112 fn draws_bayes_net_nodes_with_state_bars() {
2113 let states = vec!["yes".to_string(), "no".to_string()];
2114 let spec = [
2115 ("Rain", NodeShape::Box),
2116 ("Wet grass", NodeShape::Box),
2117 ("Water?", NodeShape::Rect),
2118 ("Cost", NodeShape::Diamond),
2119 ("Either", NodeShape::DoubleBox),
2120 ];
2121 let sizes: Vec<NodeBox> = spec
2122 .iter()
2123 .map(|(l, sh)| match sh {
2124 NodeShape::Diamond => diamond_box(l, Some("-12.5")),
2125 _ => states_box(l, None, None, &states),
2126 })
2127 .collect();
2128 let plain = node_box("Rain", None, None, false);
2130 assert_eq!(sizes[0].h, plain.h + 4.0 + 2.0 * STATE_H);
2131 assert!(sizes[0].w >= 2.0 * BOX_PAD_X + STATE_BAR_W + STATE_TEXT_W);
2132 assert!(sizes[3].w > sizes[3].h, "a diamond wider than tall");
2133 let gnodes: Vec<GraphNode> = sizes
2134 .iter()
2135 .map(|b| GraphNode {
2136 w: b.w,
2137 h: b.h,
2138 ..Default::default()
2139 })
2140 .collect();
2141 let links = [(0, 1), (2, 1), (1, 3), (0, 4)];
2142 let gedges: Vec<GraphEdge> = links
2143 .iter()
2144 .map(|&(a, b)| GraphEdge {
2145 from: a,
2146 to: b,
2147 label_w: None,
2148 })
2149 .collect();
2150 let params = LayeredParams {
2151 direction: crate::graph_layout::Direction::TopBottom,
2152 ..Default::default()
2153 };
2154 let l = layered(&gnodes, &gedges, ¶ms);
2155 let bar = |name: &str, p: f64, prior: Option<f64>, observed: bool| StateBar {
2156 name: name.to_string(),
2157 p,
2158 prior,
2159 text: format!("{:.0}%", p * 100.0),
2160 observed,
2161 was: None,
2162 };
2163 let nodes: Vec<DrawNode> = spec
2164 .iter()
2165 .zip(&sizes)
2166 .enumerate()
2167 .map(|(i, ((_, shape), b))| DrawNode {
2168 id: format!("n{i}"),
2169 shape: *shape,
2170 lines: b.lines.clone(),
2171 value: (*shape == NodeShape::Diamond).then(|| "-12.5".to_string()),
2172 stroke: (60, 60, 60),
2173 tooltip: b.lines.join(" "),
2174 attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2175 states: (*shape != NodeShape::Diamond).then(|| {
2176 if i == 1 {
2177 (
2178 vec![
2179 bar("yes", 1.0, Some(0.65), true),
2180 bar("no", 0.0, Some(0.35), false),
2181 ],
2182 (37, 99, 235),
2183 )
2184 } else {
2185 (
2186 vec![
2187 bar("yes", 0.3, Some(0.5), false),
2188 bar("no", 0.7, Some(0.5), false),
2189 ],
2190 (37, 99, 235),
2191 )
2192 }
2193 }),
2194 fill: (i == 1).then_some((230, 236, 250)),
2195 ..Default::default()
2196 })
2197 .collect();
2198 let edges: Vec<DrawEdge> = links
2199 .iter()
2200 .map(|&(a, b)| DrawEdge {
2201 colour: (90, 90, 90),
2202 width: 1.6,
2203 attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2204 ..Default::default()
2205 })
2206 .collect();
2207 let svg = draw(
2208 &l,
2209 &[],
2210 &[],
2211 &nodes,
2212 &edges,
2213 &GraphStyle::default(),
2214 crate::theme::presets::theme_void(),
2215 )
2216 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2217 .unwrap();
2218 assert_eq!(svg.matches("data-node=").count(), spec.len());
2220 for c in [
2221 "gg-graph-node-rect",
2222 "gg-graph-node-diamond",
2223 "gg-graph-node-double-box",
2224 ] {
2225 assert!(svg.contains(c), "{c}");
2226 }
2227 assert!(
2228 svg.contains("gg-graph-node-diamond-mark") && svg.contains("gg-graph-node-outline")
2229 );
2230 assert!(
2231 svg.contains("data-part=\"arrow\""),
2232 "arrowheads at the child"
2233 );
2234 assert!(
2236 svg.contains("gg-graph-node-state-bar") && svg.contains("gg-graph-node-state-prior")
2237 );
2238 assert!(svg.contains(">30%<") && svg.contains(">100%<"));
2239 assert!(svg.contains("fill=\"#E6ECFA\""), "shaded");
2241 assert!(
2242 svg.match_indices(">yes</text>")
2243 .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2244 "the observed state in bold"
2245 );
2246 assert!(svg.contains(">-12.5<"));
2248 let plain = svg
2250 .split("<rect")
2251 .find(|r| r.contains("data-node=\"n0\""))
2252 .unwrap();
2253 assert!(plain.contains("gg-graph-node\""), "{plain}");
2254 }
2255
2256 #[test]
2261 fn draws_a_policy_table_in_a_decision() {
2262 let table = NodeTable {
2263 header: vec!["Seismic".into(), "drill".into(), "don't drill".into()],
2264 rows: vec![
2265 vec!["closed".into(), "87.5".into(), "0".into()],
2266 vec!["open".into(), "22.9".into(), "0".into()],
2267 vec!["diffuse".into(), "-25.6".into(), "0".into()],
2268 vec![
2269 "a very long configuration name".into(),
2270 "1".into(),
2271 "2".into(),
2272 ],
2273 ],
2274 marked: vec![Some(1), Some(1), Some(2)],
2275 current: Some(1),
2276 keys: vec![String::new(), "drill".into(), "dont".into()],
2277 };
2278 let b = table_box("Drill?", None, None, &table);
2279 let plain = node_box("Drill?", None, None, false);
2280 assert_eq!(b.h, plain.h + 4.0 + 5.0 * STATE_H);
2282 assert!(
2283 b.w >= table.width() + 2.0 * BOX_PAD_X,
2284 "{} {}",
2285 b.w,
2286 table.width()
2287 );
2288 let bare = NodeTable {
2290 header: vec![String::new(), "EU".into()],
2291 ..table.clone()
2292 };
2293 assert_eq!(table_box("Drill?", None, None, &bare).h, b.h);
2294 let headless = NodeTable {
2295 header: Vec::new(),
2296 ..table.clone()
2297 };
2298 assert_eq!(table_box("Drill?", None, None, &headless).h, b.h - STATE_H);
2299 assert_eq!(
2300 table_box("Drill?", None, None, &NodeTable::default()),
2301 plain
2302 );
2303 let gnodes = [GraphNode {
2304 w: b.w,
2305 h: b.h,
2306 ..Default::default()
2307 }];
2308 let l = layered(&gnodes, &[], &LayeredParams::default());
2309 let nodes = [DrawNode {
2310 id: "drill".into(),
2311 shape: NodeShape::Rect,
2312 lines: b.lines.clone(),
2313 stroke: (60, 60, 60),
2314 tooltip: "Drill?".into(),
2315 attrs: vec![("node".to_string(), Some("drill".to_string()))],
2316 table: Some((table, (37, 99, 235))),
2317 ..Default::default()
2318 }];
2319 let svg = draw(
2320 &l,
2321 &[],
2322 &[],
2323 &nodes,
2324 &[],
2325 &GraphStyle::default(),
2326 crate::theme::presets::theme_void(),
2327 )
2328 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2329 .unwrap();
2330 assert!(
2331 svg.contains(">Seismic<") && svg.contains(">don't drill<"),
2332 "{svg}"
2333 );
2334 assert!(svg.contains(">closed<") && svg.contains(">-25.6<"));
2335 assert!(svg.contains(">a very long c…<"), "{svg}");
2337 assert_eq!(svg.matches("gg-graph-node-table-chosen").count(), 3);
2339 assert_eq!(svg.matches("gg-graph-node-table-mark").count(), 3);
2340 assert!(svg.contains("gg-graph-node-table-mark"));
2341 assert!(svg.contains("gg-graph-node-table-current"));
2342 assert!(
2343 svg.match_indices(">87.5</text>")
2344 .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2345 "the chosen option in bold"
2346 );
2347 assert!(
2348 svg.match_indices(">0</text>")
2349 .any(|(i, _)| !svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2350 "the others plain"
2351 );
2352 assert_eq!(svg.matches("data-state=\"dont\"").count(), 5);
2354 assert_eq!(svg.matches("data-state=\"drill\"").count(), 5);
2355 assert!(!svg
2356 .split("<text")
2357 .any(|t| t.contains(">closed<") && t.contains("data-state")));
2358 assert!(
2360 svg.match_indices(">22.9</text>")
2361 .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i]
2362 .contains("text-anchor=\"end\"")),
2363 "right-aligned"
2364 );
2365 }
2366
2367 #[test]
2372 fn draws_belief_deltas_cut_edges_and_a_hand() {
2373 let states = vec!["yes".to_string(), "no".to_string()];
2374 let plain = states_box("Rain", None, None, &states);
2375 let wide = states_box_with_deltas("Rain", None, None, &states, true);
2376 assert_eq!(wide.w, plain.w + STATE_DELTA_W, "room for the change");
2377 let gnodes = vec![
2378 GraphNode {
2379 w: wide.w,
2380 h: wide.h,
2381 ..Default::default()
2382 };
2383 2
2384 ];
2385 let l = layered(
2386 &gnodes,
2387 &[GraphEdge {
2388 from: 0,
2389 to: 1,
2390 label_w: None,
2391 }],
2392 &LayeredParams {
2393 direction: crate::graph_layout::Direction::TopBottom,
2394 ..Default::default()
2395 },
2396 );
2397 let bar = |name: &str, p: f64, was: f64| StateBar {
2398 name: name.to_string(),
2399 p,
2400 text: format!("{:.0}%", p * 100.0),
2401 was: Some(was),
2402 ..Default::default()
2403 };
2404 let nodes: Vec<DrawNode> = (0..2)
2405 .map(|i| DrawNode {
2406 id: format!("n{i}"),
2407 lines: vec![if i == 0 { "Cloudy" } else { "Rain" }.to_string()],
2408 stroke: (60, 60, 60),
2409 attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2410 states: Some((
2411 if i == 0 {
2412 vec![bar("yes", 0.5, 0.5), bar("no", 0.5, 0.5)]
2413 } else {
2414 vec![bar("yes", 0.71, 0.5), bar("no", 0.29, 0.5)]
2415 },
2416 (37, 99, 235),
2417 )),
2418 icon: (i == 0).then_some(NodeIcon::Hand),
2419 ..Default::default()
2420 })
2421 .collect();
2422 let edges = vec![DrawEdge {
2423 colour: (160, 160, 160),
2424 width: 1.6,
2425 cut: true,
2426 attrs: vec![("edge".to_string(), Some("n0>n1".to_string()))],
2427 label_attrs: vec![("to".to_string(), Some("n1".to_string()))],
2428 ..Default::default()
2429 }];
2430 let style = GraphStyle {
2431 moved: Some((245, 158, 11)),
2432 ..Default::default()
2433 };
2434 let svg = draw(
2435 &l,
2436 &[],
2437 &[],
2438 &nodes,
2439 &edges,
2440 &style,
2441 crate::theme::presets::theme_void(),
2442 )
2443 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2444 .unwrap();
2445 assert!(svg.contains(">▲21<") && svg.contains(">▼21<"), "deltas");
2447 assert_eq!(svg.matches("gg-graph-node-state-delta").count(), 2);
2448 let tint = mix(
2449 (255, 255, 255),
2450 (245, 158, 11),
2451 moved_share(&nodes[1].states.as_ref().unwrap().0).unwrap(),
2452 );
2453 assert!(
2454 svg.to_ascii_lowercase()
2455 .contains(&format!("fill=\"{}\"", hex(tint))),
2456 "tinted"
2457 );
2458 assert!(
2459 svg.contains("fill=\"#FFFFFF\"") || svg.contains("fill=\"#ffffff\""),
2460 "Cloudy untinted"
2461 );
2462 assert!(svg.contains("gg-graph-node-icon"), "hand");
2464 assert!(svg.contains("gg-graph-edge-cut"), "cut mark");
2465 assert!(svg.contains("data-state=\"yes\"") && svg.contains("data-state=\"no\""));
2467 }
2468
2469 #[test]
2470 fn js_distance_is_zero_for_the_same_and_one_for_disjoint() {
2471 assert!(js_distance(&[0.5, 0.5], &[0.5, 0.5]).abs() < 1e-12);
2472 assert!((js_distance(&[1.0, 0.0], &[0.0, 1.0]) - 1.0).abs() < 1e-12);
2473 let d = js_distance(&[0.71, 0.29], &[0.5, 0.5]);
2474 assert!(d > 0.1 && d < 0.2, "{d}");
2475 assert!((js_distance(&[2.0, 2.0], &[0.5, 0.5])).abs() < 1e-12);
2477 assert_eq!(js_distance(&[1.0], &[0.5, 0.5]), 0.0);
2478 assert_eq!(delta_text(0.71, 0.5), Some(("▲21".to_string(), true)));
2479 assert_eq!(delta_text(0.5, 0.503), None);
2480 }
2481
2482 #[test]
2483 fn wraps_long_labels_in_three_lines() {
2484 let l = wrap(
2485 "Recommend replenishment orders for every store and every week of the coming year",
2486 152.0,
2487 );
2488 assert_eq!(l.len(), 3);
2489 assert!(l[2].ends_with('…'));
2490 assert_eq!(wrap("Ingest", 152.0), ["Ingest"]);
2491 }
2492
2493 #[test]
2496 fn wraps_at_word_boundaries() {
2497 let max = BOX_MAX_W - 2.0 * BOX_PAD_X;
2498 for label in [
2499 "duckdb/community-extensions (descriptions)",
2500 "Locked DuckDB server (anofox-visualization)",
2501 "Parquet snapshot (downloads, extensions)",
2502 "fetch.sh: download, file by ISO week, merge",
2503 ] {
2504 let l = wrap(label, max);
2505 assert!(l.len() <= MAX_LINES, "{l:?}");
2506 assert!(!l.iter().any(|x| x.contains('…')), "{label}: {l:?}");
2507 let joined: String = l.concat();
2509 assert_eq!(joined.replace(' ', ""), label.replace(' ', ""), "{l:?}");
2510 for w in l.windows(2) {
2511 let end = w[0].chars().last().unwrap();
2512 let next = w[1].chars().next().unwrap();
2513 let at_space = label.contains(&format!(
2514 "{} {}",
2515 w[0].split(' ').next_back().unwrap(),
2516 w[1].split(' ').next().unwrap()
2517 ));
2518 assert!(
2519 at_space || matches!(end, '/' | '-' | '_' | '.' | ','),
2520 "{l:?} breaks at {end}{next}"
2521 );
2522 }
2523 }
2524 assert_eq!(
2525 wrap("duckdb/community-extensions (descriptions)", max),
2526 ["duckdb/community-", "extensions", "(descriptions)"]
2527 );
2528 }
2529
2530 #[test]
2531 fn node_box_grows_with_its_contents() {
2532 let plain = node_box("Ingest", None, None, false);
2533 assert_eq!((plain.w, plain.h), (BOX_MIN_W, 2.0 * BOX_PAD_Y + LINE_H));
2534 let full = node_box("Ingest", Some("1,240"), Some("late"), true);
2535 assert_eq!(full.h, plain.h + LINE_H + 20.0 + SPARK_H);
2536 assert!(full.w >= 110.0 + 2.0 * BOX_PAD_X);
2537 let long = node_box(&"word ".repeat(40), None, None, false);
2538 assert!(long.w <= BOX_MAX_W && long.lines.len() == MAX_LINES);
2539 }
2540
2541 #[test]
2543 fn edge_label_keeps_clear_of_nodes() {
2544 let node = |cx: f64, w: f64| PlacedNode {
2545 cx,
2546 cy: 0.0,
2547 w,
2548 h: 40.0,
2549 layer: 0,
2550 order: 0,
2551 };
2552 let pts = [(0.0, 0.0), (300.0, 0.0)];
2553 assert_eq!(edge_label_at(&pts, "spikes flagged", &[]), (150.0, 0.0));
2555 let nodes = [node(150.0, 60.0)];
2557 let (x, _) = edge_label_at(&pts, "spikes flagged", &nodes);
2558 let hw = edge_label_width("spikes flagged") / 2.0 + 3.0;
2559 assert!((x - 150.0).abs() >= hw + 30.0, "{x}");
2560 assert_eq!(point_at(&pts, 0.25), (75.0, 0.0));
2561 }
2562
2563 #[test]
2564 fn flow_width_is_area_true_and_rounded() {
2565 assert_eq!(flow_width(None, 10.0, EdgeLine::Solid), 1.6);
2566 assert_eq!(flow_width(Some(10.0), 10.0, EdgeLine::Solid), 7.0);
2567 assert_eq!(flow_width(Some(2.5), 10.0, EdgeLine::Solid), 4.2);
2568 assert_eq!(flow_width(None, 10.0, EdgeLine::Dots), 3.0);
2569 }
2570
2571 #[test]
2575 fn draws_marks_with_attributes_and_groups() {
2576 let labels = ["Ingest", "Model", "Publish"];
2577 let boxes: Vec<NodeBox> = labels
2578 .iter()
2579 .enumerate()
2580 .map(|(i, l)| node_box(l, (i == 1).then_some("42"), None, i == 2))
2581 .collect();
2582 let gnodes: Vec<GraphNode> = boxes
2583 .iter()
2584 .enumerate()
2585 .map(|(i, b)| GraphNode {
2586 w: b.w,
2587 h: b.h,
2588 lane: Some(i % 2),
2589 ..Default::default()
2590 })
2591 .collect();
2592 let gedges = [
2593 GraphEdge {
2594 from: 0,
2595 to: 1,
2596 label_w: Some(edge_label_width("rows")),
2597 },
2598 GraphEdge {
2599 from: 1,
2600 to: 2,
2601 label_w: None,
2602 },
2603 ];
2604 let params = LayeredParams {
2605 lanes: 2,
2606 ..Default::default()
2607 };
2608 let l = layered(&gnodes, &gedges, ¶ms);
2609 let nodes: Vec<DrawNode> = labels
2610 .iter()
2611 .zip(&boxes)
2612 .enumerate()
2613 .map(|(i, (id, b))| DrawNode {
2614 id: id.to_string(),
2615 lines: b.lines.clone(),
2616 value: (i == 1).then(|| "42".to_string()),
2617 stroke: (90, 90, 90),
2618 accent: (i == 0).then_some((200, 0, 0)),
2619 spark: (i == 2).then(|| (vec![1.0, 3.0, 2.0], (0, 0, 200))),
2620 tooltip: format!("{id}!"),
2621 attrs: vec![
2622 ("node".to_string(), Some(id.to_string())),
2623 ("value".to_string(), (i == 1).then(|| "42".to_string())),
2624 ],
2625 ..Default::default()
2626 })
2627 .collect();
2628 let edges: Vec<DrawEdge> = [(0, 1), (1, 2)]
2629 .iter()
2630 .map(|&(a, b)| DrawEdge {
2631 colour: (100, 100, 100),
2632 width: flow_width(None, 0.0, EdgeLine::Solid),
2633 line: if a == 0 {
2634 EdgeLine::Solid
2635 } else {
2636 EdgeLine::Dashed
2637 },
2638 class: (a == 1).then(|| "flowing".to_string()),
2639 tooltip: format!("{} → {}", labels[a], labels[b]),
2640 label: (a == 0).then(|| "rows".to_string()),
2641 attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2642 label_attrs: vec![("from".to_string(), Some(labels[a].to_string()))],
2643 ..Default::default()
2644 })
2645 .collect();
2646 let lanes = ["Left".to_string(), "Right".to_string()];
2647 let svg = draw(
2648 &l,
2649 &lanes,
2650 &[],
2651 &nodes,
2652 &edges,
2653 &GraphStyle::default(),
2654 crate::theme::presets::theme_void(),
2655 )
2656 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2657 .unwrap();
2658 let mut tags: Vec<(&str, bool)> = Vec::new();
2660 let mut stack: Vec<bool> = Vec::new();
2661 for part in svg.split('<').skip(1) {
2662 let tag = &part[..part.find('>').unwrap()];
2663 if tag.starts_with('/') {
2664 stack.pop();
2665 continue;
2666 }
2667 let inside = stack.iter().any(|&g| g);
2668 tags.push((tag, inside));
2669 if !tag.ends_with('/') {
2670 stack.push(tag.contains("data-of="));
2671 }
2672 }
2673 let attr = |tag: &str, name: &str| {
2674 let key = format!(" {name}=\"");
2675 tag.find(&key).map(|i| {
2676 let rest = &tag[i + key.len()..];
2677 rest[..rest.find('"').unwrap()].to_string()
2678 })
2679 };
2680 let boxes: Vec<_> = tags
2682 .iter()
2683 .filter(|(t, _)| t.contains("data-node="))
2684 .collect();
2685 assert_eq!(boxes.len(), 3);
2686 for (b, inside) in &boxes {
2687 assert!(!inside, "{b}");
2688 let id = attr(b, "data-node").unwrap();
2689 assert_eq!(attr(b, "data-value").is_some(), id == "Model", "{id}");
2690 }
2691 assert!(tags.iter().any(|(t, _)| t.contains("data-edge=\"1>2\"")
2693 && attr(t, "class").is_some_and(|c| c.contains("flowing"))));
2694 assert!(tags
2695 .iter()
2696 .any(|(t, _)| attr(t, "data-from").as_deref() == Some("Ingest")));
2697 assert!(svg.contains(" gg-graph-node\"") && svg.contains("gg-graph-edge-label"));
2698 for id in labels {
2700 assert!(svg.contains(&format!("data-of=\"{id}\"")), "{id}");
2701 }
2702 assert!(svg.contains("data-lane=\"Right\""));
2703 assert!(svg.contains(">Left<") && svg.contains(">42<"));
2704 }
2705
2706 #[test]
2709 fn forney_terminals_and_variable_edges() {
2710 use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
2711 let spec = [
2712 ("Cat", NodeShape::Glyph),
2713 ("T", NodeShape::Glyph),
2714 ("x₁", NodeShape::Terminal),
2715 ];
2716 let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
2717 assert_eq!((sizes[2].w, sizes[2].h), (TERMINAL, TERMINAL));
2718 let gnodes: Vec<GraphNode> = sizes
2719 .iter()
2720 .map(|b| GraphNode {
2721 w: b.w,
2722 h: b.h,
2723 ..Default::default()
2724 })
2725 .collect();
2726 let gedges = vec![
2727 GraphEdge {
2728 from: 0,
2729 to: 1,
2730 label_w: None,
2731 },
2732 GraphEdge {
2733 from: 1,
2734 to: 2,
2735 label_w: None,
2736 },
2737 ];
2738 let l = layered(&gnodes, &gedges, &LayeredParams::default());
2739 let nodes: Vec<DrawNode> = spec
2740 .iter()
2741 .zip(&sizes)
2742 .enumerate()
2743 .map(|(i, ((_, shape), b))| DrawNode {
2744 id: format!("n{i}"),
2745 shape: *shape,
2746 lines: b.lines.clone(),
2747 stroke: (13, 148, 136),
2748 tooltip: b.lines.join(" "),
2749 attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2750 accent: (*shape == NodeShape::Terminal).then_some((217, 119, 6)),
2752 ..Default::default()
2753 })
2754 .collect();
2755 let edges = vec![
2756 DrawEdge {
2758 colour: (13, 148, 136),
2759 width: 1.2,
2760 undirected: true,
2761 label: Some("s₀".to_string()),
2762 label_math: true,
2763 ..Default::default()
2764 },
2765 DrawEdge {
2766 colour: (13, 148, 136),
2767 width: 1.2,
2768 undirected: true,
2769 ..Default::default()
2770 },
2771 ];
2772 let render = |style: &GraphStyle| {
2773 draw(
2774 &l,
2775 &[],
2776 &[],
2777 &nodes,
2778 &edges,
2779 style,
2780 crate::theme::presets::theme_void(),
2781 )
2782 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32 + 40, l.h.ceil() as u32)
2783 .unwrap()
2784 };
2785 let math = GraphStyle {
2786 math_font: Some("STIX Two Math, serif".to_string()),
2787 ..GraphStyle::default()
2788 };
2789 let svg = render(&math);
2790 let el = |text: &str| {
2791 let at = svg
2792 .find(&format!(">{text}</text>"))
2793 .unwrap_or_else(|| panic!("{text}"));
2794 svg[svg[..at].rfind('<').unwrap()..at].to_string()
2795 };
2796 assert!(svg.contains("gg-graph-node-terminal"), "terminal mark");
2798 assert!(
2799 svg.contains("fill=\"#D97706\""),
2800 "the terminal in its accent"
2801 );
2802 let x1 = el("x₁");
2803 assert!(
2804 x1.contains("text-anchor=\"start\"") && x1.contains("italic"),
2805 "{x1}"
2806 );
2807 let t = &l.nodes[2];
2808 let lx: f64 = x1
2809 .split("x=\"")
2810 .nth(1)
2811 .unwrap()
2812 .split('"')
2813 .next()
2814 .unwrap()
2815 .parse()
2816 .unwrap();
2817 assert!(
2818 lx > t.cx + t.w / 2.0,
2819 "the label right of the square: {lx} vs {}",
2820 t.cx
2821 );
2822 let s0 = el("s₀");
2824 assert!(
2825 s0.contains("STIX Two Math") && s0.contains("italic"),
2826 "{s0}"
2827 );
2828 let plain = render(&GraphStyle::default());
2830 let at = plain.find(">s₀</text>").unwrap();
2831 assert!(!plain[plain[..at].rfind('<').unwrap()..at].contains("italic"));
2832 }
2833
2834 #[test]
2839 fn draws_a_factor_graph_with_shapes_and_a_plate() {
2840 let n = 3;
2841 let mut spec = vec![
2843 ("Beta", NodeShape::Box),
2844 ("θ", NodeShape::Circle),
2845 ("=", NodeShape::Square),
2846 ];
2847 for _ in 0..n {
2848 spec.push(("Ber", NodeShape::Box));
2849 }
2850 for _ in 0..n {
2851 spec.push(("y", NodeShape::FilledCircle));
2852 }
2853 spec.push(("2.0", NodeShape::Text));
2854 let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
2855 let mut links = vec![(0, 1, "out"), (1, 2, ""), (9, 0, "a")];
2857 for i in 0..n {
2858 links.push((2, 3 + i, "p"));
2859 links.push((3 + i, 3 + n + i, "out"));
2860 }
2861 let gnodes: Vec<GraphNode> = sizes
2862 .iter()
2863 .map(|b| GraphNode {
2864 w: b.w,
2865 h: b.h,
2866 ..Default::default()
2867 })
2868 .collect();
2869 let gedges: Vec<GraphEdge> = links
2870 .iter()
2871 .map(|&(a, b, _)| GraphEdge {
2872 from: a,
2873 to: b,
2874 label_w: None,
2875 })
2876 .collect();
2877 let params = LayeredParams {
2879 margin: 32.0,
2880 ..Default::default()
2881 };
2882 let l = layered(&gnodes, &gedges, ¶ms);
2883 let nodes: Vec<DrawNode> = spec
2884 .iter()
2885 .zip(&sizes)
2886 .enumerate()
2887 .map(|(i, ((_, shape), b))| DrawNode {
2888 id: format!("n{i}"),
2889 shape: *shape,
2890 lines: b.lines.clone(),
2891 stroke: (60, 60, 60),
2892 tooltip: b.lines.join(" "),
2893 attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2894 belief: (i == 1).then(|| (vec![0.0, 0.3, 1.0, 0.3, 0.0], (120, 80, 200))),
2896 prior: (i == 1).then(|| (vec![0.2, 0.4, 0.5, 0.4, 0.2], (150, 150, 150))),
2898 ..Default::default()
2899 })
2900 .collect();
2901 let edges: Vec<DrawEdge> = links
2902 .iter()
2903 .map(|&(a, b, iface)| DrawEdge {
2904 colour: (90, 90, 90),
2905 width: 1.2,
2906 undirected: true,
2907 label: (!iface.is_empty()).then(|| iface.to_string()),
2908 label_at: Some(if spec[b].1 == NodeShape::Box {
2910 0.8
2911 } else {
2912 0.2
2913 }),
2914 attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2915 ..Default::default()
2916 })
2917 .collect();
2918 let plates = [Plate {
2919 label: "i = 1..3".to_string(),
2920 nodes: (3..3 + 2 * n).collect(),
2921 }];
2922 let style = GraphStyle::default();
2923 let svg = draw(
2924 &l,
2925 &[],
2926 &plates,
2927 &nodes,
2928 &edges,
2929 &style,
2930 crate::theme::presets::theme_void(),
2931 )
2932 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2933 .unwrap();
2934 assert_eq!(svg.matches("data-node=").count(), spec.len());
2936 for shape in ["circle", "filled-circle", "square", "text"] {
2937 assert!(svg.contains(&format!("gg-graph-node-{shape}")), "{shape}");
2938 }
2939 assert!(
2940 !svg.contains("data-part=\"arrow\""),
2941 "an undirected edge has no arrowhead"
2942 );
2943 assert_eq!(svg.matches("data-edge=").count(), links.len());
2944 assert!(svg.contains("gg-graph-node-belief"), "belief layer");
2946 assert!(svg.contains("fill=\"#7850C8\""), "belief colour");
2947 let (pr, be) = (
2949 svg.find("gg-graph-node-prior").expect("prior layer"),
2950 svg.find("gg-graph-node-belief").unwrap(),
2951 );
2952 assert!(pr < be, "the prior under the belief");
2953 let mark = &svg[svg[..pr].rfind('<').unwrap()..pr];
2954 assert!(mark.contains("stroke-dasharray"), "dashed prior: {mark}");
2955 assert!(!svg.contains("font-style=\"italic\""), "plain labels");
2957 let math = GraphStyle {
2959 math_font: Some("STIX Two Math, serif".to_string()),
2960 glyph_fill: Some((240, 247, 246)),
2961 glyph_ink: Some((13, 148, 136)),
2962 ..style.clone()
2963 };
2964 let msvg = draw(
2965 &l,
2966 &[],
2967 &plates,
2968 &nodes,
2969 &edges,
2970 &math,
2971 crate::theme::presets::theme_void(),
2972 )
2973 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2974 .unwrap();
2975 assert!(msvg.contains("STIX Two Math"), "math font");
2976 assert!(msvg.contains("font-style=\"italic\""), "italic labels");
2977 let two = msvg.find(">2.0<").expect("the constant 2.0");
2979 let el = &msvg[msvg[..two].rfind('<').unwrap()..two];
2980 assert!(!el.contains("italic"), "upright constant: {el}");
2981 assert!(svg.contains("data-plate=\"i = 1..3\"") && svg.contains(">i = 1..3<"));
2983 assert!(svg.contains(&format!(
2985 "fill=\"{}\"",
2986 hex(style.observed_fill).to_uppercase()
2987 )));
2988 for (i, a) in l.nodes.iter().enumerate() {
2990 for b in &l.nodes[i + 1..] {
2991 let apart = (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
2992 || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0;
2993 assert!(apart, "overlap");
2994 }
2995 }
2996 let c = &l.nodes[1];
2998 assert!(svg.contains(&format!("rx=\"{:.2}\"", c.w / 2.0)), "{}", c.w);
2999 }
3000
3001 #[test]
3005 fn banded_hmm_keeps_the_state_chain_straight() {
3006 use crate::graph_layout::{banded, BandedParams};
3007 let t_n = 5;
3008 let mut spec: Vec<(String, NodeShape, usize)> = vec![
3010 ("Dir".into(), NodeShape::Glyph, 0), ("A".into(), NodeShape::Square, 0), ("Dir".into(), NodeShape::Glyph, 0), ("B".into(), NodeShape::Square, 0), ("Cat".into(), NodeShape::Glyph, 1), ("s₀".into(), NodeShape::Circle, 1), ];
3017 let mut links: Vec<(usize, usize, &str)> =
3018 vec![(0, 1, "out"), (2, 3, "out"), (4, 5, "out")];
3019 let mut prev = 5;
3020 for t in 1..=t_n {
3021 let tr = spec.len();
3022 spec.push(("T".into(), NodeShape::Glyph, 1));
3023 let eq = spec.len();
3024 spec.push((format!("s{t}"), NodeShape::Square, 1));
3025 let ob = spec.len();
3026 spec.push(("T".into(), NodeShape::Glyph, 2));
3027 let x = spec.len();
3028 spec.push((format!("x{t}"), NodeShape::FilledCircle, 2));
3029 links.extend([
3030 (prev, tr, "in"),
3031 (1, tr, "a"),
3032 (tr, eq, "out"),
3033 (eq, ob, "in"),
3034 (3, ob, "a"),
3035 (ob, x, "out"),
3036 ]);
3037 prev = eq;
3038 }
3039 let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh, _)| node_size(*sh, l)).collect();
3040 let gnodes: Vec<GraphNode> = spec
3041 .iter()
3042 .zip(&sizes)
3043 .map(|((_, _, b), s)| GraphNode {
3044 w: s.w,
3045 h: s.h,
3046 lane: Some(*b),
3047 ..Default::default()
3048 })
3049 .collect();
3050 let gedges: Vec<GraphEdge> = links
3051 .iter()
3052 .map(|&(a, b, _)| GraphEdge {
3053 from: a,
3054 to: b,
3055 label_w: None,
3056 })
3057 .collect();
3058 let l = banded(
3059 &gnodes,
3060 &gedges,
3061 &BandedParams {
3062 bands: 3,
3063 margin: 32.0,
3064 ..Default::default()
3065 },
3066 );
3067 let chain: Vec<usize> = (0..spec.len())
3069 .filter(|&i| spec[i].2 == 1 && i != 4)
3070 .collect();
3071 let y = l.nodes[chain[0]].cy;
3072 for &i in &chain {
3073 assert_eq!(l.nodes[i].cy, y, "{} off the row", spec[i].0);
3074 }
3075 for t in 0..t_n {
3077 let (eq, ob) = (6 + 4 * t + 1, 6 + 4 * t + 2);
3078 assert_eq!(l.nodes[eq].cx, l.nodes[ob].cx, "slice {t}");
3079 assert!(l.nodes[ob].cy > y);
3080 }
3081 let crosses = |(x0, y0): (f64, f64), (x1, y1): (f64, f64), n: &PlacedNode| {
3083 (0..=40).any(|k| {
3085 let t = k as f64 / 40.0;
3086 let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
3087 (x - n.cx).abs() < n.w / 2.0 - 1.0 && (y - n.cy).abs() < n.h / 2.0 - 1.0
3088 })
3089 };
3090 for (k, &(a, b, _)) in links.iter().enumerate() {
3091 for w in l.edges[k].windows(2) {
3092 for (i, n) in l.nodes.iter().enumerate() {
3093 if i != a && i != b {
3094 assert!(
3095 !crosses(w[0], w[1], n),
3096 "edge {a}->{b} crosses {}",
3097 spec[i].0
3098 );
3099 }
3100 }
3101 }
3102 }
3103 for (i, a) in l.nodes.iter().enumerate() {
3105 for b in &l.nodes[i + 1..] {
3106 assert!(
3107 (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
3108 || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0
3109 );
3110 }
3111 }
3112 let nodes: Vec<DrawNode> = spec
3113 .iter()
3114 .zip(&sizes)
3115 .enumerate()
3116 .map(|(i, ((_, shape, _), b))| DrawNode {
3117 id: format!("n{i}"),
3118 shape: *shape,
3119 lines: b.lines.clone(),
3120 stroke: (60, 60, 60),
3121 ..Default::default()
3122 })
3123 .collect();
3124 let edges: Vec<DrawEdge> = links
3125 .iter()
3126 .map(|&(_, b, iface)| DrawEdge {
3127 colour: (90, 90, 90),
3128 width: 1.2,
3129 undirected: true,
3130 label: Some(iface.to_string()),
3131 label_at: Some(if spec[b].1 == NodeShape::Glyph {
3132 0.8
3133 } else {
3134 0.2
3135 }),
3136 ..Default::default()
3137 })
3138 .collect();
3139 let lanes = ["param".to_string(), "state".to_string(), "obs".to_string()];
3140 let svg = draw(
3141 &l,
3142 &lanes,
3143 &[],
3144 &nodes,
3145 &edges,
3146 &GraphStyle::default(),
3147 crate::theme::presets::theme_void(),
3148 )
3149 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
3150 .unwrap();
3151 if let Ok(path) = std::env::var("GGPLOT_GRAPH_SVG") {
3152 std::fs::write(path, &svg).unwrap();
3153 }
3154 assert_eq!(svg.matches("data-lane=").count(), 3);
3155 }
3156}