laddu-expr 0.20.0

Amplitude analysis tools for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use std::{collections::HashSet, fmt};

use crate::{ExprGraph, ExprId, ExprMetadata, ExprNode, expression::node_children};

/// Controls how graph displays handle nodes reached through multiple paths.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum RepeatedSubtrees {
    /// Render the complete subtree at every occurrence.
    #[default]
    Expand,
    /// Render a later occurrence as a reference to the first.
    Reference,
}

/// Node categories available to visualization style selectors.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum ExprNodeKind {
    /// Real constant node.
    RealConst,
    /// Complex constant node.
    ComplexConst,
    /// Scalar parameter node.
    ScalarParam,
    /// Scalar event-data node.
    EventScalar,
    /// Four-momentum component event-data node.
    EventP4Component,
    /// Unary-operation node.
    Unary,
    /// Binary-operation node.
    Binary,
    /// N-ary addition node.
    NaryAdd,
    /// N-ary multiplication node.
    NaryMul,
    /// Complex-construction node.
    Complex,
    /// Vector-construction node.
    Vector,
    /// Matrix-construction node.
    Matrix,
    /// Vector-component node.
    Component,
    /// Matrix-element node.
    MatrixElement,
    /// Matrix-matrix multiplication node.
    MatMul,
    /// Matrix-vector multiplication node.
    MatVec,
    /// Dot-product node.
    Dot,
    /// Linear-system solution node.
    Solve,
}

impl ExprNodeKind {
    /// Returns the category corresponding to `node`.
    pub fn of(node: &ExprNode) -> Self {
        match node {
            ExprNode::RealConst(_) => Self::RealConst,
            ExprNode::ComplexConst(_) => Self::ComplexConst,
            ExprNode::ScalarParam(_) => Self::ScalarParam,
            ExprNode::EventScalar(_) => Self::EventScalar,
            ExprNode::EventP4Component { .. } => Self::EventP4Component,
            ExprNode::Unary { .. } => Self::Unary,
            ExprNode::Binary { .. } => Self::Binary,
            ExprNode::NaryAdd { .. } => Self::NaryAdd,
            ExprNode::NaryMul { .. } => Self::NaryMul,
            ExprNode::Complex { .. } => Self::Complex,
            ExprNode::Vector { .. } => Self::Vector,
            ExprNode::Matrix { .. } => Self::Matrix,
            ExprNode::Component { .. } => Self::Component,
            ExprNode::MatrixElement { .. } => Self::MatrixElement,
            ExprNode::MatMul { .. } => Self::MatMul,
            ExprNode::MatVec { .. } => Self::MatVec,
            ExprNode::Dot { .. } => Self::Dot,
            ExprNode::Solve { .. } => Self::Solve,
        }
    }
}

/// An RGB color used by tree and Graphviz displays.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct DisplayColor {
    red: u8,
    green: u8,
    blue: u8,
}

impl DisplayColor {
    /// Creates a color from red, green, and blue channels.
    pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
        Self { red, green, blue }
    }

    fn dot(self) -> String {
        format!("#{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
    }

    fn ansi_foreground(self) -> String {
        format!("\x1b[38;2;{};{};{}m", self.red, self.green, self.blue)
    }
}

/// Optional foreground, fill, and border colors for a displayed node.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct NodeStyle {
    /// Text color.
    pub foreground: Option<DisplayColor>,
    /// Background or fill color.
    pub fill: Option<DisplayColor>,
    /// Outline color.
    pub border: Option<DisplayColor>,
}

impl NodeStyle {
    /// Creates a style with no color overrides.
    pub const fn new() -> Self {
        Self {
            foreground: None,
            fill: None,
            border: None,
        }
    }

    /// Sets the text color.
    pub const fn with_foreground(mut self, color: DisplayColor) -> Self {
        self.foreground = Some(color);
        self
    }

    /// Sets the background or fill color.
    pub const fn with_fill(mut self, color: DisplayColor) -> Self {
        self.fill = Some(color);
        self
    }

    /// Sets the outline color.
    pub const fn with_border(mut self, color: DisplayColor) -> Self {
        self.border = Some(color);
        self
    }

    fn overlay(&mut self, other: Self) {
        if other.foreground.is_some() {
            self.foreground = other.foreground;
        }
        if other.fill.is_some() {
            self.fill = other.fill;
        }
        if other.border.is_some() {
            self.border = other.border;
        }
    }
}

/// Predicate selecting expression nodes for a [`NodeStyleRule`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NodeSelector {
    /// Select every node.
    Any,
    /// Select nodes in a category.
    Kind(ExprNodeKind),
    /// Select nodes with a matching metadata or source name.
    Name(String),
    /// Select nodes carrying a metadata tag.
    Tag(String),
}

impl NodeSelector {
    fn matches(&self, node: &ExprNode, metadata: Option<&ExprMetadata>) -> bool {
        match self {
            Self::Any => true,
            Self::Kind(kind) => *kind == ExprNodeKind::of(node),
            Self::Name(name) => {
                metadata.and_then(ExprMetadata::name) == Some(name.as_str())
                    || match node {
                        ExprNode::ScalarParam(parameter) => parameter.name() == name,
                        ExprNode::EventScalar(node_name)
                        | ExprNode::EventP4Component {
                            name: node_name, ..
                        } => node_name.as_ref() == name,
                        _ => false,
                    }
            }
            Self::Tag(tag) => metadata.is_some_and(|metadata| metadata.has_tag(tag)),
        }
    }
}

/// A selector and the style to overlay on matching nodes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NodeStyleRule {
    /// Predicate used to select nodes.
    pub selector: NodeSelector,
    /// Style overlaid on selected nodes.
    pub style: NodeStyle,
}

impl NodeStyleRule {
    /// Creates a style rule from a selector and style.
    pub fn new(selector: NodeSelector, style: NodeStyle) -> Self {
        Self { selector, style }
    }
}

/// Built-in color palette for expression graphs.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ColorPreset {
    /// Colors selected for light backgrounds.
    Light,
    /// Colors selected for dark backgrounds.
    Dark,
}

#[derive(Clone, Debug, Default)]
struct DisplayOptions {
    repeated_subtrees: RepeatedSubtrees,
    rules: Vec<NodeStyleRule>,
}

impl DisplayOptions {
    fn with_preset(&mut self, preset: ColorPreset) {
        let (constant, parameter, event, operation, linear_algebra) = match preset {
            ColorPreset::Light => (
                DisplayColor::rgb(88, 96, 105),
                DisplayColor::rgb(0, 92, 197),
                DisplayColor::rgb(3, 102, 214),
                DisplayColor::rgb(130, 80, 223),
                DisplayColor::rgb(207, 34, 46),
            ),
            ColorPreset::Dark => (
                DisplayColor::rgb(139, 148, 158),
                DisplayColor::rgb(88, 166, 255),
                DisplayColor::rgb(121, 192, 255),
                DisplayColor::rgb(210, 168, 255),
                DisplayColor::rgb(255, 123, 114),
            ),
        };
        let style = |color| NodeStyle::new().with_foreground(color).with_border(color);
        for kind in [ExprNodeKind::RealConst, ExprNodeKind::ComplexConst] {
            self.rules.push(NodeStyleRule::new(
                NodeSelector::Kind(kind),
                style(constant),
            ));
        }
        self.rules.push(NodeStyleRule::new(
            NodeSelector::Kind(ExprNodeKind::ScalarParam),
            style(parameter),
        ));
        for kind in [ExprNodeKind::EventScalar, ExprNodeKind::EventP4Component] {
            self.rules
                .push(NodeStyleRule::new(NodeSelector::Kind(kind), style(event)));
        }
        for kind in [
            ExprNodeKind::Unary,
            ExprNodeKind::Binary,
            ExprNodeKind::NaryAdd,
            ExprNodeKind::NaryMul,
            ExprNodeKind::Complex,
            ExprNodeKind::Vector,
            ExprNodeKind::Matrix,
            ExprNodeKind::Component,
            ExprNodeKind::MatrixElement,
        ] {
            self.rules.push(NodeStyleRule::new(
                NodeSelector::Kind(kind),
                style(operation),
            ));
        }
        for kind in [
            ExprNodeKind::MatMul,
            ExprNodeKind::MatVec,
            ExprNodeKind::Dot,
            ExprNodeKind::Solve,
        ] {
            self.rules.push(NodeStyleRule::new(
                NodeSelector::Kind(kind),
                style(linear_algebra),
            ));
        }
    }

    fn resolve(&self, graph: &ExprGraph, id: ExprId, node: &ExprNode) -> NodeStyle {
        let mut style = NodeStyle::default();
        let metadata = graph.metadata(id);
        for rule in &self.rules {
            if rule.selector.matches(node, metadata) {
                style.overlay(rule.style);
            }
        }
        style
    }
}

macro_rules! display_builder_methods {
    () => {
        /// Sets how nodes reached through multiple paths are rendered.
        pub fn repeated_subtrees(mut self, repeated_subtrees: RepeatedSubtrees) -> Self {
            self.options.repeated_subtrees = repeated_subtrees;
            self
        }

        /// Chooses between fully expanding and referencing repeated subtrees.
        pub fn expand_repeated(self, expand: bool) -> Self {
            self.repeated_subtrees(if expand {
                RepeatedSubtrees::Expand
            } else {
                RepeatedSubtrees::Reference
            })
        }

        /// Adds the style rules from a built-in color palette.
        pub fn with_preset(mut self, preset: ColorPreset) -> Self {
            self.options.with_preset(preset);
            self
        }

        /// Appends a node style rule.
        ///
        /// Later matching rules override fields set by earlier rules.
        pub fn with_style_rule(mut self, rule: NodeStyleRule) -> Self {
            self.options.rules.push(rule);
            self
        }
    };
}

/// Configurable indented-tree display for an [`ExprGraph`].
pub struct ExprGraphTreeDisplay<'a> {
    graph: &'a ExprGraph,
    options: DisplayOptions,
}

impl<'a> ExprGraphTreeDisplay<'a> {
    pub(crate) fn new(graph: &'a ExprGraph) -> Self {
        Self {
            graph,
            options: DisplayOptions::default(),
        }
    }

    display_builder_methods!();

    fn fmt_node(
        &self,
        f: &mut fmt::Formatter<'_>,
        id: ExprId,
        prefix: &str,
        edge: Option<(&str, bool)>,
        visited: &mut HashSet<ExprId>,
    ) -> fmt::Result {
        let Some(node) = self.graph.node(id) else {
            return write_tree_line(f, prefix, edge, &format!("#{} <missing node>", id.index()));
        };
        let repeated = !visited.insert(id);
        let mut line = if repeated && self.options.repeated_subtrees == RepeatedSubtrees::Reference
        {
            format!("#{0} <reference to #{0}>", id.index())
        } else {
            self.graph.node_label(id, node)
        };
        if let Some(color) = self.options.resolve(self.graph, id, node).foreground {
            line = format!("{}{line}\x1b[0m", color.ansi_foreground());
        }
        write_tree_line(f, prefix, edge, &line)?;
        if repeated && self.options.repeated_subtrees == RepeatedSubtrees::Reference {
            return Ok(());
        }

        let children = node_children(node);
        let child_prefix = match edge {
            Some((_, true)) => format!("{prefix}   "),
            Some((_, false)) => format!("{prefix}┃  "),
            None => prefix.to_owned(),
        };
        for (index, (label, child)) in children.iter().enumerate() {
            self.fmt_node(
                f,
                *child,
                &child_prefix,
                Some((label, index + 1 == children.len())),
                visited,
            )?;
        }
        Ok(())
    }
}

impl fmt::Display for ExprGraphTreeDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "ExprGraph(root=#{})", self.graph.root().index())?;
        self.fmt_node(f, self.graph.root(), "", None, &mut HashSet::new())
    }
}

/// Configurable Graphviz DOT display for an [`ExprGraph`].
pub struct ExprGraphDotDisplay<'a> {
    graph: &'a ExprGraph,
    options: DisplayOptions,
}

impl<'a> ExprGraphDotDisplay<'a> {
    pub(crate) fn new(graph: &'a ExprGraph) -> Self {
        Self {
            graph,
            options: DisplayOptions::default(),
        }
    }

    display_builder_methods!();

    #[cfg(feature = "svg")]
    /// Renders the generated Graphviz graph as an SVG document.
    ///
    /// # Errors
    ///
    /// Returns [`GraphRenderError::Dot`] when the generated Graphviz DOT
    /// source cannot be parsed.
    pub fn render_svg(&self) -> Result<String, GraphRenderError> {
        use layout::{backends::svg::SVGWriter, gv};

        let dot = self.to_string();
        let mut parser = gv::DotParser::new(&dot);
        let graph = parser.process().map_err(GraphRenderError::Dot)?;
        let mut builder = gv::GraphBuilder::new();
        builder.visit_graph(&graph);
        let mut graph = builder.get();
        let mut svg = SVGWriter::new();
        graph.do_it(false, false, false, &mut svg);
        Ok(svg.finalize())
    }

    fn node_attributes(&self, id: ExprId, node: &ExprNode) -> String {
        let mut attributes = vec![format!(
            "label=\"{}\"",
            escape_dot(&self.graph.node_label(id, node))
        )];
        let style = self.options.resolve(self.graph, id, node);
        if let Some(color) = style.foreground {
            attributes.push(format!("fontcolor=\"{}\"", color.dot()));
        }
        if let Some(color) = style.border {
            attributes.push(format!("color=\"{}\"", color.dot()));
        }
        if let Some(color) = style.fill {
            attributes.push(format!("fillcolor=\"{}\"", color.dot()));
            attributes.push("style=filled".to_owned());
        }
        attributes.join(", ")
    }

    fn write_expanded(
        &self,
        f: &mut fmt::Formatter<'_>,
        id: ExprId,
        occurrence: &mut usize,
    ) -> fmt::Result {
        let current = *occurrence;
        *occurrence += 1;
        let Some(node) = self.graph.node(id) else {
            return Ok(());
        };
        writeln!(f, "  n{current} [{}];", self.node_attributes(id, node))?;
        for (label, child) in node_children(node) {
            let child_occurrence = *occurrence;
            self.write_expanded(f, child, occurrence)?;
            writeln!(
                f,
                "  n{current} -> n{child_occurrence} [label=\"{}\"];",
                escape_dot(&label)
            )?;
        }
        Ok(())
    }

    fn write_shared(
        &self,
        f: &mut fmt::Formatter<'_>,
        id: ExprId,
        visited: &mut HashSet<ExprId>,
    ) -> fmt::Result {
        if !visited.insert(id) {
            return Ok(());
        }
        let Some(node) = self.graph.node(id) else {
            return Ok(());
        };
        writeln!(f, "  n{} [{}];", id.index(), self.node_attributes(id, node))?;
        for (label, child) in node_children(node) {
            self.write_shared(f, child, visited)?;
            writeln!(
                f,
                "  n{} -> n{} [label=\"{}\"];",
                id.index(),
                child.index(),
                escape_dot(&label)
            )?;
        }
        Ok(())
    }
}

#[cfg(feature = "svg")]
/// Errors produced while rendering an expression graph.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum GraphRenderError {
    /// The generated Graphviz DOT source could not be parsed.
    #[error("failed to parse generated DOT: {0}")]
    Dot(String),
}

impl fmt::Display for ExprGraphDotDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "digraph ExprGraph {{")?;
        match self.options.repeated_subtrees {
            RepeatedSubtrees::Expand => self.write_expanded(f, self.graph.root(), &mut 0)?,
            RepeatedSubtrees::Reference => {
                self.write_shared(f, self.graph.root(), &mut HashSet::new())?
            }
        }
        writeln!(f, "}}")
    }
}

fn write_tree_line(
    f: &mut fmt::Formatter<'_>,
    prefix: &str,
    edge: Option<(&str, bool)>,
    text: &str,
) -> fmt::Result {
    if let Some((label, is_last)) = edge {
        let connector = if is_last { "┗" } else { "┣" };
        writeln!(f, "{prefix}{connector} {label}: {text}")
    } else {
        writeln!(f, "{text}")
    }
}

fn escape_dot(value: &str) -> String {
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event_scalar;

    fn shared_graph() -> ExprGraph {
        let shared = event_scalar("x").named("shared").tagged("data");
        ((shared.clone() + 1.0) * (shared + 2.0)).to_graph()
    }

    #[test]
    fn tree_and_dot_expand_repeated_subtrees_without_color_by_default() {
        let graph = shared_graph();
        let shared_id = graph
            .nodes()
            .iter()
            .position(|node| matches!(node, ExprNode::EventScalar(name) if name.as_ref() == "x"))
            .unwrap();
        let needle = format!("#{shared_id} EventScalar(x)");
        let tree = graph.display_tree().to_string();
        let dot = graph.display_dot().to_string();

        assert_eq!(tree.matches(&needle).count(), 2);
        assert_eq!(dot.matches(&needle).count(), 2);
        assert!(!tree.contains("\x1b["));
        assert!(!dot.contains("fontcolor="));
        assert!(!dot.contains("fillcolor="));
    }

    #[test]
    fn reference_mode_suppresses_repeated_tree_expansion_and_emits_a_shared_dag() {
        let graph = shared_graph();
        let tree = graph
            .display_tree()
            .repeated_subtrees(RepeatedSubtrees::Reference)
            .to_string();
        let dot = graph.display_dot().expand_repeated(false).to_string();

        assert_eq!(tree.matches("EventScalar(x)").count(), 1);
        assert_eq!(tree.matches("<reference to #").count(), 1);
        assert_eq!(dot.matches("EventScalar(x)").count(), 1);
        assert_eq!(dot.matches(" -> ").count(), 6);
    }

    #[test]
    fn later_style_rules_override_matching_preset_fields() {
        let graph = shared_graph();
        let override_color = DisplayColor::rgb(1, 2, 3);
        let rule = NodeStyleRule::new(
            NodeSelector::Tag("data".to_owned()),
            NodeStyle::new().with_foreground(override_color),
        );
        let tree = graph
            .display_tree()
            .with_preset(ColorPreset::Light)
            .with_style_rule(rule.clone())
            .to_string();
        let dot = graph
            .display_dot()
            .with_preset(ColorPreset::Light)
            .with_style_rule(rule)
            .to_string();

        assert!(tree.contains("\x1b[38;2;1;2;3m"));
        assert!(dot.contains("fontcolor=\"#010203\""));
    }

    #[test]
    fn dot_escapes_metadata_and_event_labels() {
        let graph = event_scalar("x\\\"y").named("quoted\"name").to_graph();
        let dot = graph.display_dot().to_string();

        assert!(dot.contains("x\\\\\\\"y"));
        assert!(dot.contains("quoted\\\"name"));
    }

    #[cfg(feature = "svg")]
    #[test]
    fn dot_display_renders_svg_in_process() {
        let svg = shared_graph()
            .display_dot()
            .with_preset(ColorPreset::Light)
            .render_svg()
            .unwrap();

        assert!(svg.contains("<svg"));
        assert!(svg.contains("</svg>"));
    }
}