Skip to main content

feynkit_graph/
display.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    fmt::Write,
4};
5
6use crate::{DiagramError, FeynmanDiagram, LoopMomentumBasis};
7use linnet::half_edge::{
8    EdgeAccessors,
9    involution::{EdgeIndex, Flow, Orientation},
10    subgraph::{SuBitGraph, SubSetLike},
11};
12use symbolica::atom::AtomCore;
13
14pub(crate) fn typst_string(value: &str) -> String {
15    let mut output = String::with_capacity(value.len() + 2);
16    output.push('"');
17    for character in value.chars() {
18        match character {
19            '\\' => output.push_str("\\\\"),
20            '"' => output.push_str("\\\""),
21            '\n' => output.push_str("\\n"),
22            '\r' => output.push_str("\\r"),
23            '\t' => output.push_str("\\t"),
24            character if character.is_control() => {
25                write!(output, "\\u{{{:x}}}", character as u32)
26                    .expect("writing to a string cannot fail");
27            }
28            character => output.push(character),
29        }
30    }
31    output.push('"');
32    output
33}
34
35impl FeynmanDiagram {
36    /// The `particle-map` binding of the shared physics styles for this diagram's particles.
37    pub(crate) fn typst_particle_map(&self) -> String {
38        let mut output = String::from("#let particle-map = (\n");
39        let particles = self
40            .edges()
41            .map(|(_, _, edge)| edge.particle)
42            .collect::<BTreeSet<_>>();
43        if particles.is_empty() {
44            output.push(':');
45        }
46        for particle in particles {
47            let particle = self
48                .model()
49                .particle_by_id(particle)
50                .expect("validated particle ID");
51            writeln!(
52                output,
53                "  {}: {},",
54                typst_string(&particle.name),
55                particle.generate_edge_typst_dict(self.model())
56            )
57            .expect("writing to a string cannot fail");
58        }
59        output.push_str(")\n");
60        output
61    }
62
63    /// Emit a complete Typst document that renders this diagram with Linnest.
64    ///
65    /// The document imports the canonical Linnest package tree at
66    /// `crates/linnest/typst`, which must be available below the Typst project
67    /// root together with its sibling Kurvst package and the shared physics
68    /// styles in `assets/embedded/drawing/templates`. Particle spin, color,
69    /// charge, mass, and TeX names select line patterns, arrows, and labels.
70    /// Interaction vertices retain their native identifiers. Amplitude external
71    /// legs are dangling half-edges and retain their names, indices, and
72    /// incoming/outgoing states as edge data.
73    ///
74    /// GammaLoop's shared physics layout owns particle styling, label measurement,
75    /// force settings, and left/right amplitude placement. Finalized cross sections
76    /// contain paired initial-state edges, opened for drawing by default. Set
77    /// `options.split-initial-state` to false to retain their sewn appearance.
78    /// Inspection and highlighting always refer to the original diagram.
79    ///
80    /// A native half-edge selection highlights the corresponding structural
81    /// halves while retaining the complete graph and its particle styles.
82    /// The complement is faded and dotted; an empty selection fades everything.
83    /// Selected isolated vertices are supplied separately from the half-edges.
84    /// `config` is a trusted native Typst configuration expression, serialized by
85    /// Linnet at the Python boundary. The optional basis is validated against this
86    /// graph; its signatures supply momentum labels and SVG inspection metadata.
87    pub fn to_linnest(
88        &self,
89        highlight: Option<&SuBitGraph>,
90        isolated: &BTreeSet<usize>,
91        lmb: Option<&LoopMomentumBasis>,
92        config: &str,
93    ) -> Result<String, DiagramError> {
94        let basis = lmb.unwrap_or_else(|| self.loop_momentum_basis());
95        if lmb.is_some() {
96            basis.validate(self)?;
97        }
98        let internal_vertices: Vec<_> = self.vertices().collect();
99        let internal_ids: BTreeMap<_, _> = internal_vertices
100            .iter()
101            .map(|(id, _)| (*id, id.0))
102            .collect();
103
104        let mut output = String::from(
105            r##"#set page(width: auto, height: auto, margin: (x: 2mm, y: 2mm), fill: none)
106#set text(size: 9pt)
107#import "crates/linnest/typst/src/graph.typ" as graph
108#import "crates/linnest/typst/src/subgraph.typ" as subgraph
109#import "crates/linnest/typst/src/render/layout.typ" as renderer
110#import "assets/embedded/drawing/templates/layout-core.typ" as physics-layout
111#import "assets/embedded/drawing/templates/physics-edge-style.typ" as physics
112#import physics: palette, massive, massless, dashed, dotted, source-stroke, sink-stroke, fermion-flow, wave, coil, zigzag
113#import graph: build, edge, node, sink, source
114#set text(fill: palette.ink)
115
116"##,
117        );
118        output.push_str(&self.typst_particle_map());
119        output.push_str("\n#context {\n  let raw = build({\n");
120
121        for (id, vertex) in &internal_vertices {
122            let dense_id = internal_ids[id];
123            let interaction = vertex
124                .interaction
125                .and_then(|rule| self.model().vertex_rule_by_id(rule).ok())
126                .map(|rule| typst_string(&rule.name))
127                .unwrap_or_else(|| "none".to_owned());
128            let incident = self
129                .edges()
130                .filter(|(_, endpoints, _)| {
131                    endpoints.source == Some(*id) || endpoints.target == Some(*id)
132                })
133                .map(|(edge, _, _)| format!("{},", edge.0))
134                .collect::<String>();
135            writeln!(
136                output,
137                "    node(<v{dense_id}>, id: {dense_id}, inspection: (node: {}, edges: ({incident})), feynkit-name: {}, interaction: {}, numerator: {})",
138                id.0,
139                typst_string(&vertex.name),
140                interaction,
141                typst_string(&crate::NumeratorInterface::export(&vertex.numerator).0.to_canonical_string()),
142            )
143            .expect("writing to a string cannot fail");
144        }
145
146        for (id, endpoints, edge) in self.edges() {
147            let particle = self
148                .model()
149                .particle_by_id(edge.particle)
150                .expect("validated diagram particle IDs resolve in the owned model");
151            let source_internal = endpoints.source.map(|vertex| internal_ids[&vertex]);
152            let target_internal = endpoints.target.map(|vertex| internal_ids[&vertex]);
153            let orientation = match self.underlying().orientation(EdgeIndex(id.0)) {
154                Orientation::Default => "default",
155                Orientation::Reversed => "reversed",
156                Orientation::Undirected => "undirected",
157            };
158            let endpoint_spec = match (source_internal, target_internal) {
159                (Some(source), Some(target)) => {
160                    format!("source(<v{source}>), <e{}>, sink(<v{target}>)", id.0)
161                }
162                (Some(source), None) => format!("source(<v{source}>), <e{}>", id.0),
163                (None, Some(target)) => format!("<e{}>, sink(<v{target}>)", id.0),
164                (None, None) => unreachable!("every native edge has an incident interaction"),
165            };
166            let external_metadata = edge.external.as_ref().map(|external| format!(
167                ", external-state: {:?}, external-index: {}, external-name: {}, external-connection: {}",
168                external.state.as_str(), external.index, typst_string(&external.name), external.connection,
169            )).unwrap_or_default();
170            let cut_metadata = edge
171                .external
172                .as_ref()
173                .filter(|_| endpoints.source.is_some() && endpoints.target.is_some())
174                .map(|external| format!(", is_cut: {}", external.connection))
175                .unwrap_or_default();
176            let momentum = &basis.edge_signatures[&id];
177            let (loops, external) = momentum.integer_coefficients();
178            let loops = loops
179                .iter()
180                .map(|value| format!("{value},"))
181                .collect::<String>();
182            let external = external
183                .iter()
184                .map(|value| format!("{value},"))
185                .collect::<String>();
186            writeln!(
187                output,
188                "    edge({endpoint_spec}, id: {}, orientation: {orientation:?}, particle: {}, pdg: {}, directed: {}, numerator: {}, inspection: (edge: {edge_id}, source: {}, sink: {}), momentum: {}, momentum-signature: (loops: ({loops}), external: ({external})){external_metadata}{cut_metadata})",
189                id.0,
190                typst_string(&particle.name),
191                particle.pdg_code,
192                edge.directed,
193                typst_string(&crate::NumeratorInterface::export(&edge.numerator).0.to_canonical_string()),
194                endpoints.source.map(|vertex| vertex.0.to_string()).unwrap_or_else(|| "none".to_owned()),
195                endpoints.target.map(|vertex| vertex.0.to_string()).unwrap_or_else(|| "none".to_owned()),
196                typst_string(&momentum.format_momentum()),
197                edge_id = id.0,
198            )
199            .expect("writing to a string cannot fail");
200        }
201
202        writeln!(
203            output,
204            "  }}, name: {}, data: (symmetry-factor: {}, overall-factor: {}, numerator: {}, loop-count: {}))",
205            typst_string(self.name()),
206            self.symmetry_factor(),
207            typst_string(&self.overall_factor().to_canonical_string()),
208            typst_string(&crate::NumeratorInterface::export(self.numerator()).0.to_canonical_string()),
209            self.loop_count(),
210        )
211        .expect("writing to a string cannot fail");
212        // Match the edge-ordered public Linnet view before any display-only cuts.
213        output.push_str(
214            r#"  raw = graph.map(raw, edge: e => (inspection: e.data.inspection + (
215    source-hedge: if e.source == none { none } else { e.source.hedge },
216    sink-hedge: if e.sink == none { none } else { e.sink.hedge },
217  )))
218"#,
219        );
220        let (highlight_options, node_style) = if let Some(highlight) = highlight {
221            let mut source = String::new();
222            let mut sink = String::new();
223            let mut nodes = isolated.clone();
224            for hedge in highlight.included_iter() {
225                nodes.insert(self.graph.node_id(hedge).0);
226                let selected = match self.graph.flow(hedge) {
227                    Flow::Source => &mut source,
228                    Flow::Sink => &mut sink,
229                };
230                write!(selected, "{}, ", self.graph[&hedge].0)
231                    .expect("writing to a string cannot fail");
232            }
233            // Typst rebuilds the graph in edge order. Structural edge halves
234            // preserve selection identity even when native hedge IDs differ.
235            writeln!(
236                output,
237                "  let highlighted = subgraph.select(raw, source: ({source}), sink: ({sink}))"
238            )
239            .expect("writing to a string cannot fail");
240            let nodes = nodes
241                .into_iter()
242                .map(|node| format!("{node}, "))
243                .collect::<String>();
244            writeln!(
245                output,
246                r##"  let selected-nodes = ({nodes})
247  let selected-stroke = rgb("#ffd166") + 1.2pt
248  let selected-edge-style = edge => (stroke: physics.source-style(edge, map: particle-map).stroke + (paint: rgb("#ffd166")))
249  let outside-stroke = (paint: rgb("#777777").transparentize(55%), thickness: 0.6pt, dash: "dotted")"##
250            )
251            .expect("writing to a string cannot fail");
252            (
253                "    draw: (subgraph: ((subgraph: subgraph.complement(raw, highlighted), edge-style: (stroke: outside-stroke)), (subgraph: highlighted, edge-style: selected-edge-style)), subgraph-edge-underlay: false),\n",
254                "node-style: node => physics.node-style + if node.vid in selected-nodes { (stroke: selected-stroke) } else { (stroke: outside-stroke) }",
255            )
256        } else {
257            ("    :\n", ":")
258        };
259        write!(
260            output,
261            r##"
262  let config = {config}
263  let options = config.at("options", default: (:))
264  let options = (label-fill: palette.ink) + if options == none {{ (:) }} else {{ options }}
265  if not ("mode", "amplitude-mode", "cross-section-mode").any(key => options.keys().contains(key)) {{
266    options += (mode: "{}",)
267  }}
268  // Open only the sewn initial-state connections; final-state cut edges remain paired.
269  if options.at("split-initial-state", default: true) {{
270    let initial = graph.edges(raw).filter(e => e.source != none and e.sink != none and e.data.at("is_cut", default: none) != none).map(e => e.edge)
271    if initial.len() > 0 {{
272      raw = graph.cut(raw, left: subgraph.select(raw, sink: initial), right: subgraph.select(raw, source: initial))
273{remap_highlight}    }}
274  }}
275  let style = config.at("style", default: (:))
276  let node-label-default = if options.at("show-node-index", default: false) or options.at("debug", default: false) {{ (:) }} else {{ (node-label: none) }}
277  let style = node-label-default + ({node_style}) + if style == none {{ (:) }} else {{ style }}
278  let draw = config.at("draw", default: (:))
279  let draw = if draw == none {{ (:) }} else {{ draw }}
280  let drawing = (
281{highlight_options}  )
282  physics-layout.render-layout(
283    config + (options: options, style: style, draw: drawing.at("draw", default: (:)) + draw),
284    input: raw,
285    graph: graph,
286    renderer: renderer,
287    physics: physics,
288    edge-style: (map: particle-map, default-edge: physics.default-edge),
289  )
290}}
291"##,
292            if self.cuts().is_empty() && !self.is_selection_only() {
293                "amplitude"
294            } else {
295                "cross-section"
296            },
297            remap_highlight = if highlight.is_some() {
298                "      highlighted = subgraph.select(raw, hedges: graph.edges(raw).map(e => (e.source, e.sink).filter(h => h != none and subgraph.contains(highlighted, h.origin)).map(h => h.hedge)).flatten())\n"
299            } else { "" },
300        )
301        .expect("writing to a string cannot fail");
302        Ok(output)
303    }
304}
305
306#[cfg(test)]
307pub(crate) mod tests {
308    use std::{collections::BTreeSet, sync::Arc};
309
310    use linnet::half_edge::{
311        involution::Hedge,
312        subgraph::{ModifySubSet, SuBitGraph},
313    };
314
315    use crate::{DiagramEdge, DiagramVertex, ExternalLeg, ExternalState, FeynmanDiagram};
316    use feynkit_model::Model;
317
318    fn display_model() -> Arc<Model> {
319        Arc::new(Model::from_json(
320            r#"{
321                "name":"display","restriction":null,"orders":[],
322                "parameters":[
323                    {"name":"ZERO","lhablock":null,"lhacode":null,"nature":"internal","parameter_type":"real","value":[0.0,0.0],"expression":null},
324                    {"name":"M","lhablock":"MASS","lhacode":[25],"nature":"external","parameter_type":"real","value":[1.0,0.0],"expression":null}
325                ],
326                "particles":[{"pdg_code":25,"name":"phi","antiname":"phi","spin":1,"color":1,"mass":"M","width":"ZERO","texname":"phi","antitexname":"phi","charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0}],
327                "propagators":[{"name":"phi_prop","particle":"phi","numerator":"1","denominator":"P^2-M^2"}],
328                "lorentz_structures":[
329                    {"name":"L3","spins":[1,1,1],"structure":"1"},
330                    {"name":"L1","spins":[1],"structure":"1"}
331                ],
332                "couplings":[],
333                "vertex_rules":[
334                    {"name":"V_1","particles":["phi","phi","phi"],"color_structures":["1"],"lorentz_structures":["L3"],"couplings":[[null]]},
335                    {"name":"V_3","particles":["phi","phi","phi"],"color_structures":["1"],"lorentz_structures":["L3"],"couplings":[[null]]},
336                    {"name":"V\"1","particles":["phi"],"color_structures":["1"],"lorentz_structures":["L1"],"couplings":[[null]]}
337                ]
338            }"#,
339        ).unwrap())
340    }
341
342    pub(crate) fn one_loop() -> FeynmanDiagram {
343        let model = display_model();
344        let rule = model.vertex_rule_id("V_1").unwrap();
345        let particle = model.particle_id("phi").unwrap();
346        let mut builder = FeynmanDiagram::builder(model, "bubble");
347        let mut incoming = DiagramEdge::new(particle, false);
348        incoming.external = Some(ExternalLeg {
349            name: "p1".into(),
350            index: 0,
351            state: ExternalState::Incoming,
352            connection: 0,
353        });
354        let mut outgoing = DiagramEdge::new(particle, false);
355        outgoing.external = Some(ExternalLeg {
356            name: "p2".into(),
357            index: 1,
358            state: ExternalState::Outgoing,
359            connection: 1,
360        });
361        let left = builder.add_vertex(DiagramVertex::interaction("left", rule));
362        let right = builder.add_vertex(DiagramVertex::interaction("right", rule));
363        let scalar = || DiagramEdge::new(particle, false);
364        builder.add_edge(None, left, incoming).unwrap();
365        builder.add_edge(left, right, scalar()).unwrap();
366        builder.add_edge(left, right, scalar()).unwrap();
367        builder.add_edge(right, None, outgoing).unwrap();
368        builder.build().unwrap()
369    }
370
371    #[test]
372    fn emits_deterministic_complete_linnest_source_for_a_loop() {
373        let diagram = one_loop();
374        let source = diagram
375            .to_linnest(None, &BTreeSet::new(), None, "(:)")
376            .unwrap();
377
378        assert_eq!(
379            source,
380            diagram
381                .to_linnest(None, &BTreeSet::new(), None, "(:)")
382                .unwrap()
383        );
384        assert!(source.starts_with("#set page(width: auto"));
385        assert!(source.contains("#import \"crates/linnest/typst/src/graph.typ\" as graph"));
386        assert_eq!(source.matches("    node(").count(), 2);
387        assert!(source.contains("node(<v0>, id: 0"));
388        assert!(source.contains("node(<v1>, id: 1"));
389        assert!(source.contains("edge(<e0>, sink(<v0>), id: 0"));
390        assert!(source.contains("edge(source(<v1>), <e3>, id: 3"));
391        assert_eq!(source.matches("edge(source(<v0>), <e").count(), 2);
392        assert!(source.contains("physics-layout.render-layout("));
393        assert!(source.contains("mode: \"amplitude\""));
394        assert!(!source.contains("is_cut:"));
395        assert!(!source.contains("pos: graph.pos"));
396        assert!(source.contains("dash: dashed"));
397        assert!(source.ends_with("}\n"));
398    }
399
400    #[test]
401    fn focuses_exact_native_halves_without_changing_graph_or_layout() {
402        let diagram = one_loop();
403        let baseline = diagram
404            .to_linnest(None, &BTreeSet::new(), None, "(:)")
405            .unwrap();
406        let empty = diagram.graph.empty_subgraph::<SuBitGraph>();
407        let empty_source = diagram
408            .to_linnest(Some(&empty), &BTreeSet::new(), None, "(:)")
409            .unwrap();
410        assert_ne!(empty_source, baseline);
411        assert!(
412            empty_source
413                .contains("  let highlighted = subgraph.select(raw, source: (), sink: ())\n")
414        );
415        assert!(empty_source.contains("  let selected-nodes = ()\n"));
416
417        // Select the incoming and outgoing dangling legs, plus opposite halves
418        // of the two parallel internal edges. Their partners stay unselected.
419        let mut selected = empty;
420        for hedge in [Hedge(0), Hedge(1), Hedge(4), Hedge(5)] {
421            selected.add(hedge);
422        }
423        let source = diagram
424            .to_linnest(Some(&selected), &BTreeSet::new(), None, "(:)")
425            .unwrap();
426        let selection =
427            "  let highlighted = subgraph.select(raw, source: (1, 3, ), sink: (0, 2, ))\n";
428        assert!(source.contains(selection));
429        assert!(source.contains("  let selected-nodes = (0, 1, )\n"));
430        assert!(source.contains("subgraph.complement(raw, highlighted)"));
431        assert!(source.contains("subgraph-edge-underlay: false"));
432        assert!(source.contains("transparentize(55%)"));
433        assert!(source.contains("dash: \"dotted\""));
434        assert!(source.contains("physics.source-style(edge, map: particle-map).stroke"));
435
436        // The complete topology and particle styles precede the selection
437        // decoration; the same layout settings follow it.
438        let (graph_source, _) = baseline.split_once("  let config = ").unwrap();
439        assert!(source.starts_with(graph_source.trim_end()));
440        assert!(source.contains("input: raw"));
441        assert!(source.contains("config.at(\"draw\", default: (:))"));
442        assert_eq!(
443            diagram
444                .to_linnest(None, &BTreeSet::new(), None, "(:)")
445                .unwrap(),
446            baseline
447        );
448    }
449
450    #[test]
451    fn focuses_selected_isolated_vertices_in_the_complete_graph() {
452        let mut builder = FeynmanDiagram::builder(display_model(), "isolated");
453        for name in ["selected", "outside"] {
454            builder.add_vertex(DiagramVertex {
455                name: name.to_owned(),
456                interaction: None,
457                numerator: idenso::tensor::SymbolicTensor::infer(symbolica::atom::Atom::one())
458                    .unwrap(),
459            });
460        }
461        let diagram = builder.build().unwrap();
462        let empty = diagram.graph.empty_subgraph::<SuBitGraph>();
463        let selected = diagram
464            .to_linnest(Some(&empty), &BTreeSet::from([0]), None, "(:)")
465            .unwrap();
466        assert_eq!(selected.matches("    node(").count(), 2);
467        assert!(selected.contains("  let selected-nodes = (0, )\n"));
468        assert!(selected.contains("node.vid in selected-nodes"));
469        assert!(selected.contains("else { (stroke: outside-stroke) }"));
470    }
471
472    #[test]
473    fn delegates_external_placement_without_reordering_edges() {
474        let model = display_model();
475        let rule = model.vertex_rule_id("V_3").unwrap();
476        let particle = model.particle_id("phi").unwrap();
477        let mut builder = FeynmanDiagram::builder(model, "one-to-two");
478        let interaction = builder.add_vertex(DiagramVertex::interaction("v", rule));
479        for (name, index, state) in [
480            ("in", 0, ExternalState::Incoming),
481            ("out-high", 2, ExternalState::Outgoing),
482            ("out-low", 1, ExternalState::Outgoing),
483        ] {
484            let mut edge = DiagramEdge::new(particle, false);
485            edge.external = Some(ExternalLeg {
486                name: name.into(),
487                index,
488                state,
489                connection: index,
490            });
491            match state {
492                ExternalState::Incoming => builder.add_edge(None, interaction, edge),
493                ExternalState::Outgoing => builder.add_edge(interaction, None, edge),
494            }
495            .unwrap();
496        }
497        let source = builder
498            .build()
499            .unwrap()
500            .to_linnest(None, &BTreeSet::new(), None, "(:)")
501            .unwrap();
502
503        let low = source.find("external-name: \"out-low\"").unwrap();
504        let high = source.find("external-name: \"out-high\"").unwrap();
505        assert!(low > high, "edge emission remains stable by edge id");
506        assert!(source.contains("mode: \"amplitude\""));
507        assert!(!source.contains("pos: graph.pos"));
508    }
509
510    #[test]
511    fn escapes_typst_strings_and_preserves_directed_orientation() {
512        let model = display_model();
513        let rule = model.vertex_rule_id("V\"1").unwrap();
514        let particle = model.particle_id("phi").unwrap();
515        let mut builder = FeynmanDiagram::builder(model, "quote \" and \\ slash");
516        let interaction = builder.add_vertex(DiagramVertex::interaction("v", rule));
517        let mut incoming = DiagramEdge::new(particle, true);
518        incoming.external = Some(ExternalLeg {
519            name: "p\n1".into(),
520            index: 0,
521            state: ExternalState::Incoming,
522            connection: 0,
523        });
524        builder.add_edge(None, interaction, incoming).unwrap();
525        builder.edge_orientations =
526            Some(vec![linnet::half_edge::involution::Orientation::Reversed]);
527        let source = builder
528            .build()
529            .unwrap()
530            .to_linnest(None, &BTreeSet::new(), None, "(:)")
531            .unwrap();
532
533        assert!(source.contains("name: \"quote \\\" and \\\\ slash\""));
534        assert!(source.contains("feynkit-name: \"v\""));
535        assert!(source.contains("interaction: \"V\\\"1\""));
536        assert!(source.contains("external-name: \"p\\n1\""));
537        assert!(source.contains("orientation: \"reversed\""));
538        assert!(!source.contains("p\n1"));
539    }
540}